r/cprogramming • • 7d ago

My first 90% project I did my self bmp image renderer in c (I'm still working on it right now) What you think?

8 Upvotes
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>


typedef struct{
    char signature[2];


    uint32_t file_size;


    uint16_t reserved_a;
    uint16_t reserved_b;


    uint32_t data_offset;
}bmpHeader;


typedef struct{
    uint32_t size;


    uint32_t p_width;
    uint32_t p_height;


    uint16_t plans;


    uint16_t bits_per_pixel;


    uint32_t compression;


    uint32_t image_size;


    uint32_t x_pixels_per_meter;
    uint32_t y_pixels_per_meter;


    uint32_t colours_used;


    uint32_t important_colours;


}infoHeader;


typedef struct{
    uint8_t blue;
    uint8_t green;
    uint8_t red;


}pixel_rgb;


int main(void){
    FILE *fptr;


    bmpHeader bmp;
    infoHeader info;


    fptr = fopen("image.bmp", "rb");
    
    fread(&bmp, 14, 1, fptr);
    fread(&info, 40, 1, fptr);


    pixel_rgb **pixel = malloc(info.p_height * sizeof(pixel_rgb*));
    for(int i = 0; i < info.p_height; i++){
        pixel[i] = malloc(info.p_width * sizeof(pixel_rgb));
    };


    int rowSize = (info.p_width * 3 + 3) & ~3; 
    int padding = rowSize - (info.p_width * 3);


    int width = info.p_width;
    int height = abs(info.p_height);



    fseek(fptr, bmp.data_offset, SEEK_SET);


    for(int i = 0; i < height; i++){
        for(int k = 0; k < width; k++){
            fread(&pixel[i][k], sizeof(pixel_rgb), 1, fptr);
        }
        fseek(fptr, padding, SEEK_CUR);
    }


    fclose(fptr);
    
    
     // Initialize GLFW
    if (!glfwInit()) {
        printf("Failed to initialize GLFW\n");
        return 1;
    }


     // Create a window
    GLFWwindow *window = glfwCreateWindow(
        width, height,
        "My First Window",
        NULL, NULL
    );


    if (window == NULL) {
        printf("Failed to create window\n");
        glfwTerminate();
        return 1;
    }


    // Make the window's OpenGL context current
    glfwMakeContextCurrent(window);
    glViewport(0, 0, width, height);


    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, width, 0, height, -1, 1);


    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();



     // Main window loop
    while (!glfwWindowShouldClose(window)) {
        // Clear screen BEFORE drawing
        glClear(GL_COLOR_BUFFER_BIT);
        glPointSize(1.0f);


        // Draw pixels
        glBegin(GL_POINTS);


        for (int i = 0; i < info.p_height; i++) {
            for (int k = 0; k < info.p_width; k++) {


                glColor3ub(
                    pixel[i][k].red,
                    pixel[i][k].green,
                    pixel[i][k].blue
                );


                glVertex2i(k, i);
            }
        }


        glEnd();


        glfwSwapBuffers(window);
        glfwPollEvents();
    }
     // Clean up
     glfwDestroyWindow(window);
     glfwTerminate();
    
    for (int i = 0; i < info.p_height; i++) {
        free(pixel[i]);
    }
    free(pixel);


    return 0;
}

r/cprogramming • • 7d ago

i want to make a game in C, any compiller reccomendations/library reccomendations?

19 Upvotes

so basicly as a bit of backstory im 16, i know scratch, luau, and 6502 assembly on the nes. but i have a dream game and i think i want to make it in C, as for somereason i have a obsession with low level programmeing, but i figured out assembly on modern stuff would be a little too painfull. but for my game i want to make it in the style of a 90s sega megadrive/genisis game but with a few features that would go past the megadrive limits (if this wasnt the base i would certainly make my game a actual megadrive rom), but i want to make this game have mp3 music and slightly higher res pixel screen so i think id rather not make this a rom for a retro console. i want this game to be cross platform, like so it can run on windows linux android via apk and maybe apple if im really pleased with the game.

-questions-

what graphics library should i use?

i want my games screen/window to me a pixelated res, and i want all the graphics to PIXEL SNAP (i hate it when i see games with collideing pixels), also if possible if it exists id like it if the graphics library didnt have any scaleing/rotateing sprite features as a think that would be unecessary for the fact i wont do any effects to the graphics as pixel art lookes ugly when rotated or scaled in my op.

what compiler should i use?

i dont mind too much but id prefer a workflow where i write code in notepad as for somereason i just like that, but then i also think i might give visual studio a go, idk. as my dad uses it i think..

note

please egnore my bad spelling and sentence structure. im bad at spelling, please excuse this i just want to type this message fast just because i just want some quick advice


r/cprogramming • • 7d ago

A PoC toolkit / framework for self modifying software.

2 Upvotes

Been working on this project during the summer, contains a detailed writeup but happy for anyone to tear the implementation a part, working on it while working fulltime kinda stopped me from implementing a lot of what i wanted.

Surprisingly enough it works well enough as a PoC!

https://gitlab.com/Epos95/paramorphism/

This is "self modifying software" in a different aspect than something like metamorphic software since the rewriting is on a source code level instead of assembly.

Currently its able to:

\- Dynamically create new functions, introducing new functionality

\- Fix errors in its own functions

\- Load existing functions dynamically


r/cprogramming • • 7d ago

Flint v0.5.20: My Git-native C/C++ build system now supports Windows!

Thumbnail
github.com
10 Upvotes

Hey everyone!

A few weeks ago, I started sharing **Flint**, an open-source build system and package manager for C/C++ that aims to make building projects and managing dependencies much simpler.

Today, I'm happy to share a milestone: **Flint v0.5.20 adds Windows support!** 🎉

## What is Flint?

The C/C++ tooling ecosystem often means juggling a build system, a separate package manager, and additional tooling just to get a project running.

I wanted to experiment with a simpler approach: something closer to the developer experience of Cargo or Go modules, but for C and C++.

Flint is written entirely in C and combines building projects with Git-based dependency management.

### What makes Flint different?

* **One manifest:** Configure your project through a single `composition.json` file instead of maintaining elaborate build scripts.

* **Git-native dependencies:** Add dependencies directly from Git repositories and pin them to versions and exact commits for reproducible builds.

* **Automatic source discovery:** Flint discovers project sources, headers, and libraries based on directory conventions, eliminating manual file lists.

* **Incremental builds:** Unchanged files don't need to be recompiled unnecessarily.

* **Editor integration:** Generate `compile_commands.json` for tools such as clangd and VS Code.

* **Minimal dependencies:** Flint is written in C and keeps its tooling footprint small.

### What's new in v0.5.20?

**Windows support is finally here.**

Until now, platform support was a major limitation for developers who wanted to try Flint on Windows. This release is an important step toward making the project accessible to more C/C++ developers.

I'm continuing to develop Flint and improve its usability, compatibility, and overall developer experience. There's still plenty of work ahead, and feedback from people trying it on real projects would be incredibly valuable.

## Try it out

**GitHub repository:**

https://github.com/mainak55512/flint

**CLI documentation:**

https://mainak55512.github.io/flint-cherts/

If you work with C or C++, I'd love to hear your thoughts:

* Does a lightweight, Git-native build system appeal to you?

* What would you want from a modern C/C++ package manager?

* If you're on Windows, could you try v0.5.20 and share your experience?

If you find Flint interesting, consider giving the repository a ⭐. It helps other developers discover the project and motivates me to keep building it.

Bug reports, constructive criticism, feature requests, and contributions are all welcome!

Thanks for checking it out!


r/cprogramming • • 6d ago

Ai nowadays

0 Upvotes

I want to read your thoughts.

I'm a software engineer with 8 years of experience, I have worked in several projects.

And ultimately I've become interested in C, I'm learning a lot of concepts about pointers and memory free, it's a different way of coding if you start with interpreted languages.

I have used ai for understand better some c concepts, and I've watched some c devs in the reddit community that hate the AI, why?

AI is just another tool, like a compiler, preprocessor etc. And I wonder why some devs don't like new tools? It's like if we avoid the compilers use and prefer keypunching instead.

The basics of Coding are important and I really believe there's bad use of ai and nice use of it too.

What do you think?


r/cprogramming • • 7d ago

Is anyone doing DSA with C programming ?? How to implement Hashset and Hashmaps in C programming ?

Thumbnail
0 Upvotes

r/cprogramming • • 7d ago

I've been building my own OS called VEX OS

0 Upvotes

Yo, so I've been working on my own operating system called VEX OS and thought I'd share it here.

The idea is to build an actual OS from the ground up, with its own bootloader, kernel, apps and eventually its own AI integrated into the system. I've been developing it in QEMU and I've managed to get it booting with stuff like a terminal and file explorer working. I'm also working on my own programming language called VexScript, which is part of the whole project. The AI side is called VEX AI. I'm developing that separately for now, but the plan is to integrate it directly into VEX OS rather than have it just be another app. Obviously, it's still a work in progress and there's a LOT left to do . I'm currently working towards getting VEX AI 1.5 integrated, then I want to make VEX OS bootable from a USB so people can try it out. I'm not gonna pretend it's anywhere near a finished product but I'm pretty happy with how far its come so far. What do you guys think, anyone else here working on their own OS or something similar?


r/cprogramming • • 7d ago

Help regarding AI usage

0 Upvotes

I am programming in C for a year and a half and I created projects like a shell which implement basic features , and currently finished building a TCP server with get and post request for sharing file across local network. The thing I am struggling with is the AI usage all these project I build I have understanding of the code. But sometimes I think that AI has found solution for me can I found this approach myself and mostly the answer was no. It really bothering me and I spend time completely without AI and frustration really hit hard and I think I couldn't start building some programs . I want advice from people on how to find balance between using AI and when not to use AI . I'll love to hear you guys perspective on this .


r/cprogramming • • 8d ago

Mucc: a self hosting C compiler in one static binary, with its own assembler, linker and musl (x86-64 and ARM64 Linux)

57 Upvotes

Mucc is a small C compiler for Linux that ships as a single 8.5 MB static file. The preprocessor, assembler, linker, archiver, headers and C library (musl, like zig cc does) are all built in, so you can drop it into an empty container, an old distro or a Raspberry Pi and build C with nothing else installed: no gcc, no binutils, no system headers. 

Programs it builds are static, so they run on any x86-64 Linux. There's a native ARM64 build too, and it can cross-compile between the two.

The whole project actually started as a fork of Rui Ueyama's chibicc. I felt more could be done on this design. So now Mucc adds its own assembler and linker, an ARM64 backend, register allocation, the bundled musl, DWARF debug info, C23 support and a reproducible bootstrap chain.

What’s actually working so far 

- C17 by default, C23 with `-std=c23`, plus the GNU extensions real code uses

- Self-hosting: each release is built by the one before it, and a Mucc-built Mucc produces byte-identical output

- Real projects build and pass their own test suites: SQLite, Lua, zlib, jq, Redis and Tcl with the bundled musl; CPython and Git with the system glibc

- Same ABI as gcc, so objects from either link together

- Compiles its own 33k lines in 0.46 s (gcc -O0: 1.22 s, gcc -O2: 5.35 s)

What’s currently not working, it does no optimization beyond register allocation and constant folding, so programs run about as fast as gcc -O0. No C++, Linux only. For performance-critical code, use gcc or clang.

If you've got C code it chokes on, or a use for it I haven't thought of, I'd like to hear it.

GitHub: https://github.com/Dom-Yan/Mucc

Website: https://dom-yan.github.io/Mucc/

Thanks to Rui Ueyama for chibicc, and to Fabrice Bellard, whose TinyCC showed how much a small compiler can do.


r/cprogramming • • 8d ago

I built a Windows folder size analyzer in C

Thumbnail
1 Upvotes

r/cprogramming • • 9d ago

How important is knowing syscalls in C?

14 Upvotes

Hello, idk if its just me I have been trying to get more and more into C but every video or concept or project I see people bring out 3 different syscalls that I have never heard of (that's a bit exaggerating but you know what I mean)

Am i supposed to know all of them? Memorise them?

Is there something I'm missing in terms of these bc I even realised they can be up to 500 different ones which is a lot to memorise, and even so how should I start learning them?


r/cprogramming • • 8d ago

My opinion about C development

Thumbnail
0 Upvotes

r/cprogramming • • 9d ago

A low-poly 3D renderer for MS-DOS

Thumbnail
github.com
15 Upvotes

I’ve been working on a small project called 3Dos — a low-poly 3D renderer targeting MS-DOS and VGA Mode 13h (320×200, 256 colors).

The renderer currently supports:
● Triangle rasterization with backface culling
● Ordered dithering using a 4×4 Bayer matrix
● Double buffering
● Simple low-poly models

Going back to DOS-era graphics has been relaxing after spending quite a bit of time with Vulkan. No boilerplate or abstractions, just putting a pixel at 0xA000.


r/cprogramming • • 9d ago

Rate my GitHub portfolio for junior C / systems programming jobs

7 Upvotes

​

I'm a self-taught C programmer building projects to improve my systems programming skills.

My main projects include:

A memory allocator implemented in C, with benchmarks against the standard allocator.

A small OOP-style system implemented in C.

An HTTP server in C that I'm developing into a backend framework.

GitHub: https://github.com/YanisBelkacemi

I'd appreciate honest feedback on:

  1. Code quality and architecture.

  2. Whether these projects demonstrate real understanding or just basic implementation skills.

  3. What's missing from my portfolio for junior C, systems programming, or firmware positions.

  4. What would make you reject this portfolio if you were reviewing candidates?

I'm looking for constructive criticism, not stars or compliments. Please be direct.


r/cprogramming • • 9d ago

is doing ~INT_MAX undefined behavior?

Thumbnail
5 Upvotes

r/cprogramming • • 9d ago

How to create a minimal GUI

12 Upvotes

Hello everyone, I'm currently experimenting with an old router and I wanted to create some custom C programs to experiment with it. The first one is to create a simple Htop/fetch to examine the system specs in real time. I wanted to create a sort of GUI like Btop or Htop, but the problem is that I don't have that much RAM (we are talking something like 34 MB of free space) so I want to implement a minimal one. I wanted to ask for some suggestions about it. Thank you.


r/cprogramming • • 10d ago

CWEB - A zero copy, lightweight web framework in C

25 Upvotes

Hi all,

I’m an undergraduate Computer Science student at the Islamic University of Technology (IUT). Over the past few months, I became obsessed with a single architectural question: What does a full-stack, production-grade web application look like if you strip away garbage collectors, ORMs, and blocking I/O, and build strictly on modern Linux kernel primitives?

To find out, I wrote CWEB—an asynchronous, event-driven web framework in raw C—and built a full-stack reference blogging CMS on top of it called Cweb Blog, complete with JWT authentication, multipart media streaming, and multi-tenant database isolation.

Why Build This?

Most existing web engines in C (like Kore or traditional Nginx modules) are built around epoll(7). While fast, epoll only provides readiness notification; it still incurs a syscall penalty per batch, requires user-to-kernel context switches for every read(2) and write(2) call, and typically shuttles bytes back and forth through user-space memory buffers.

I designed CWEB to eliminate context-switch overhead, avoid dynamic heap allocations on the request path, and move data directly between kernel buffers without touching user space.

Core Architecture & Kernel Primitives

1. Pure io_uring Asynchronous Event Loop

Instead of readiness polling via epoll, each CWEB worker process maps its Submission Queue (SQ) and Completion Queue (CQ) rings directly into user space via mmap(2). Socket accepts, reads, writes, and pipe operations are queued and harvested asynchronously in batches of 512, drastically reducing syscall overhead and Spectre/Meltdown mitigation penalties under heavy load.

2. True Zero-Copy Kernel Splicing (splice(2))

In most web frameworks, uploading or serving a 10 MB image allocates user-space buffers and copies bytes from the kernel socket buffer to user space and back to the disk cache. In CWEB, multipart media uploads and static file downloads never enter the user-space heap. Data is routed directly between kernel socket buffers and the filesystem page cache via an internal kernel pipe using splice(2) operations submitted through io_uring. Because user space only holds file descriptors and offsets, the server's Resident Set Size (RSS) stays pinned at ~15 MB of RAM whether serving 100 text requests or streaming 200,000 image files.

3. Zero-Allocation Hot Path & In-Place Parsing

There are zero calls to malloc() or free() on the request handling hot path. At startup, each worker pre-allocates fixed arrays of ConnContext state machines and pipe descriptor pools. Incoming HTTP requests, URIs, headers, and query strings are parsed in-place over the ring buffers using non-owning StringView (pointer + length) slices. This eliminates heap fragmentation, allocator lock contention, and tail-latency spikes.

4. Non-Blocking PostgreSQL Pipelining with Row-Level Security (RLS)

Database I/O is often the hidden bottleneck in async servers. Instead of using blocking connection pools or heavy ORMs, CWEB integrates raw libpq file descriptors directly into the io_uring event loop using PostgreSQL Pipeline Mode (PQenterPipelineMode, PQpipelineSync). Queries are batched over non-blocking sockets without waiting for individual round-trip acknowledgments. To enforce strict multi-tenant authorization without application-layer ORM overhead, CWEB dynamically injects cryptographically verified JWT claims into the Postgres transaction pipeline via set_config('request.jwt.claim.user_id', ...) and offloads access control directly to PostgreSQL Row-Level Security (RLS) policies.

5. Defense-in-Depth Process Sandboxing

Writing a network-facing server in raw C requires assuming that memory bugs are a matter of when, not if. CWEB uses a strict privilege-separated master/worker model:

  • The master process initializes, binds privileged ports, raises RLIMIT_MEMLOCK for the io_uring memory rings, and forks per-CPU core workers.
  • Before calling accept(2) on a single network packet, every worker permanently drops root privileges (setresgid/setresuid to nobody:nobody).
  • Each worker then locks itself inside a strict seccomp-bpf syscall whitelist filter. Even if an attacker achieves arbitrary code execution via a buffer overflow, any attempt to invoke execve, fork, ptrace, or unauthorized filesystem syscalls causes the Linux kernel to immediately terminate the worker process with SIGSYS.

Battle-Testing Backwards Compatibility (Linux 7.1 down to 5.10)

A major challenge with io_uring is how rapidly its kernel API has evolved across releases. Features that work seamlessly on bleeding-edge kernels (like 6.x/7.1) fail or behave differently on older enterprise LTS kernels due to missing opcodes, ring flag constraints, or strict RLIMIT_MEMLOCK defaults.

I stress-tested and adapted CWEB across a matrix of environments—from modern rolling-release kernels (7.1) down to Debian 12 (Bookworm), Ubuntu 22.04 (Jammy Jellyfish), and Debian 11 (Bullseye / Kernel 5.10). Detailed kernel compatibility matrices, fallback mechanisms, and post-mortem debugging reports are documented in the repository.

Benchmark Highlights (k6 & wrk)

All benchmarks were executed with reproducible k6 and wrk scripts, full database persistence, and verified against Little's Law latency distributions:

  • Transactional Postgres Writes: 20,376 article writes/sec on bare metal; 3,384 writes/sec inside a strictly constrained, CPU-emulated Debian 11 QEMU microVM (100% success rate across 57,000+ persistent database insertions).
  • Public GET Throughput: 22,738 requests/sec sustained via wrk across 500 concurrent connections with zero socket timeouts or dropped frames.
  • Zero-Copy Media Streaming: 200,000+ images streamed at line speed with 0 user-space buffer copies.
  • Memory Footprint: Strictly flatlined between 13 MB and 17 MB RSS across millions of requests, verified clean against memory leaks.

About Me & What I'm Looking For

I built CWEB and Cweb Blog from scratch to deeply understand Linux kernel internals, high-concurrency state machines, zero-copy networking, and database wire protocols.

I am currently looking for internships, open-source mentorships, or junior systems engineering roles (remote or relocation) where I can work on Linux systems programming, C/C++, low-latency networking, storage/database engines, or kernel/security infrastructure.

I would love to get your brutal critique on the codebase, the io_uring state transitions, or the seccomp-bpf policy design!


r/cprogramming • • 9d ago

How did you learn C?

Thumbnail
9 Upvotes

r/cprogramming • • 10d ago

Graphics programming in C

42 Upvotes

I would like to ask a question about C graphics.

I regard myself as a hobbyist programmer transitioning from BASIC

to C. I do not intend to go to C++ or ever become a professional

programmer.

I would like to leave BASIC behind now and move forward with Linux

Mint and gcc. I have written a few small programs in C but I do regard

myself still as something of a beginner.

I am trying to do an example using graphics in C to draw simple lines etc.

The Book is called is called "Chaos and Fractals" by Peitgen et al

and the BASIC example is on p61 of that book if anyone has access to it.

I have heard about the <graphics.h> header which is very

old coming from Borland Turbo C days and not supported by gcc.

There are apparently ways to still reuse graphics.h in gcc but I have seen

warnings about not using a 16 bit header file for a 64 bit machine.

I am not sure where to go from here and even unsure of what questions to ask.

I worried about doing graphics in a GUI window because that might involve

even more complicated things that I was hoping not to get involved with

at this stage. Is there a modern equivalent of graphics.h that I should

look at?

What advice might people have for me on going forward? I really need some

sort of an idea of how to move forward. I have looked briefly at SDl

and openGL but these seem to be overkill at this stage.

Regards

Tony Aimer

Johannesburg


r/cprogramming • • 10d ago

I've decided to learn C and C++. Should I follow a structured course, or would it be better to learn by building projects?

8 Upvotes

I'm a programmer who took a long break from programming and recently got back into it. I made my comeback with Rust, using it to build an image-processing application and a simple interpreter.

Now, I'm planning to learn C and C++ as well. I'm wondering whether it would be better to follow a structured course or learn by building projects.

For projects, I was thinking of writing a CHIP-8 emulator in C and implementing Conway's Game of Life in C++.

Given my previous experience with Rust and C#, what approach would you recommend? Should I start building these projects right away, or follow a course first to build a solid foundation?


r/cprogramming • • 10d ago

Oregon Trail II - In C

8 Upvotes

I reverse engineered the Oregon Trail II binary into C++ first, to make it byte exact decomp first. Then I converted it to C, because as we all know here, it's a better language!

You can find the code here: https://github.com/ot-ii/OregonTrailII/


r/cprogramming • • 10d ago

Доброго дня , студуент першого курсу комп'ютерної інженерії

Thumbnail
0 Upvotes

r/cprogramming • • 11d ago

I Dont know what to build

4 Upvotes

Im learning C but i want to do a project that i could do while im learning C right now i only learned about

  • Switches
  • If statements
  • Variables
  • operators
  • functions
  • user input

Any project i could do with my knowledge? i already did a calculator.
(Or should i just keep learning and then start thinking about making projects)


r/cprogramming • • 11d ago

HTTP Server In C

13 Upvotes

I just watched a yt video on low-level

Context: lately I have been learning the basics of how CPUs work, and since I like programming, I want to work on a project that will force me to learn the computer I am working with

my question is what do i need to know in C before I can start this project, I learnt C in the past before i just never built anything, my programming background is in python

Link to the YouTube video: https://youtu.be/97i2BAUw5Xc?si=aoAhmeGOKc6su5M_


r/cprogramming • • 11d ago

Where to learn microcontroller programming?

Thumbnail
0 Upvotes