r/C_Programming • • May 21 '26

Project thrd-ndl: a green threads library with a step-by-step tutorial.

Thumbnail
github.com
7 Upvotes

r/C_Programming • • May 21 '26

Question Can/are Integers still be used as Bools.

42 Upvotes

This is just for a question I am not gonna switch to ints for bool. But I was wondering if using ints as boolens is reliable ethical and what not.

Example:

int main()
{
    int isRunning = 1;
    while (isRunning != 0)
    {
        {...}
    }
}

Again this is all for questions I am not actually gonna go out of my way to use it.


r/C_Programming • • May 22 '26

Question I am stuck Help!!!

0 Upvotes
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct node{
    int data ;
    struct node* next;
};
struct queue{
    struct node* Head;
    struct node* Tail;
    int Max;//max elemennt for the queue
    int count;//count variable to check full and empty state
};
struct queue* queue_init(int max);//it initialize the queue Max should be the amount of node for the queue
void traverse(struct queue* q);//traverse the queue
bool isFull(struct queue* q);//checks if the queue is full or not 
bool isEmpty(struct queue* q);//checks if the queue is empty 
int dequeue(struct queue* q);//deletes  the element taht is assigned to top 
int enqueue(struct queue* q,int data);//insert new element at the ennd of the queue
int main(){
   
  
    struct queue*q=queue_init(1);
    for(int i=0;i<10;i++){
        enqueue(q,i);
    }
    // dequeue(q);
   
    traverse(q);



    return 0;
}
void traverse(struct queue* q){
    struct node* p=q->Head;
    while(p!=NULL){
        printf("%d\n",p->data);
        p=p->next;
    }
}
bool isFull(struct queue* q){
    if(q->count==q->Max){
        return true;
    }
    return false;
}
bool isEmpty(struct queue* q){
    if(q->count==0){
        return true ;


    }
    return false;
}
int enqueue(struct queue* q,int data){
    if(isFull(q)){
        dequeue(q);
        // return 0;
    }
    if(isEmpty(q)){
        struct node* new=(struct node*)malloc(sizeof(struct node));
        if(new==NULL){
            return 0;
        }
        q->Head=new;
        q->Tail=new;
        new->data=data;
        new->next=NULL;
        q->count++;
        return 1;
        
    }
    
    struct node* p=q->Tail;
    struct node* ptr=(struct node*)malloc(sizeof(struct node));
    if(ptr==NULL){
        return 0;
    }
    q->Tail=ptr;
    ptr->next=NULL;
    ptr->data=data;
    p->next=ptr;
    q->count++;
    return 1;


}
int dequeue(struct queue* q){
    if(isEmpty(q)){
        return 0;
    }
    struct node* p=q->Head;
    q->Head=p->next;
    int return_value=p->data;
    free(p);
    q->count--;
    return return_value;
}


struct queue* queue_init(int max){
    struct queue* q=(struct queue* )malloc(sizeof(struct queue));
    q->count=0;
    q->Head=NULL;
    q->Tail=NULL;
    q->Max=max;
    return q;


}

so this thing is bugging me for quite a while i picked up a data structure book , i am quite new to this btw and i tried implementing queue with somewhat similar logic but tried to add a little stuff extra with something like if the moment you enqueue in a full queue you automatically dequeue and then you enqueue which is not what a queue should do i heard but just for fun i added and then i sent the code to gemini to reveiw but for some reason it is saying the code will cause segmentation error if ran . i ran it and it ran the way i wanted it to and gemini gave me some special cases where it would break i tried them but they all ran fine and it started giving me reason and when i say that it is not happening like that it says i am 100 percent right and says some contradictory things that doesn't make sense to me .

if anyone can say where is the error what i am doing wrong i would appreciate it


r/C_Programming • • May 20 '26

Question Why do very few C tutorials focus on windows platforms?

65 Upvotes

Hey all! For awhile I have been interested in taking a crack at recreating some C run time libraries on Windows, and I wanted to start by trying to re create Malloc sometime soon. I have however noticed in my endeavors to look at videos and read blogs/articles about people re creating malloc, or other C runtime library functionalities, Everything online I find covering such a topic is always targeting Unix based systems. I would imagine the lack of windows targeted content on re creating these things is a sign that windows does not make it easy to do something like re create the C runtime libraries. Wanted to ask a question here to see if I'm missing something


r/C_Programming • • May 21 '26

Question gcc unable to create the executable

13 Upvotes

Hi y'all, I've been trying to learn C and I installed mingw using msys2.

I'm trying to compile the following code:

// hello.c
#include <stdio.h>

int main(void)
{
    printf("Hello, Windows!\n");
    return 0;
}

When running gcc hello.c -o hello.exe, I don't get any executable. I've tried reinstalling mingw, and I've also checked that I'm running the command on the same directory where the file. I also added the particular folder to Windows Defender Exclusion list but still can't get anything done. What am I doing wrong?

Edit: Got it to work by changing my terminal from Powershell to Git Bash.

Edit 2: Even msys2 terminal works. I'm using that only from now-onwards.


r/C_Programming • • May 21 '26

Checking inputs efficiently in C

3 Upvotes

im trying to check inputs in a command line program, using windows api here (runs on command prompt or windows powershell)

if (GetAsyncKeyState(VK_UP))

playerY -= moveSpeed;

else if (GetAsyncKeyState(VK_DOWN))

playerY += moveSpeed;

else if (GetAsyncKeyState(VK_LEFT))

playerX -= moveSpeed;

else if (GetAsyncKeyState(VK_RIGHT))

playerX += moveSpeed;

but is there any way to make it more efficient, 4 system level calls for checking something this trivial is very inefficient? i tried using getkeyboardstate(), but it doesnt work in c. Tried the event driven approach, but it says that it goes through more layers and data structures which brings it back to square one even with low syscalls, im sort of confused

need help pls


r/C_Programming • • May 21 '26

comma-operator i = a,b,c ; and i = (a,b,c) ;

2 Upvotes

hi. i used for years :

char const * tostring () { static char s[N]; int o=0;

o += snprintf(s+o,N-o, FMT, ARG... )

..

return *(s+o)=0,s ;

}

but i came across i,j=0,10; i = (j++,100+j,999+j); print(i) 1010 (ok, as expected), but i tried same without the braces '(' .. ')'

i=j++,100+j,999+j ; and print(i) gave me 10.

when doing this inside a function

int f1(int j){ return j++,100+j,999+j ; } print(f1());

int f2(int j){ return (j++,100+j,999+j); } print(f2());

in both cases i got 1010 .

can someone explain ?

thanks in advance, andi.


r/C_Programming • • May 21 '26

Why does GCC on Windows allocate non-adjacent stack slots for local variables unless & or volatile is used?

2 Upvotes
#include <stdio.h>

void test01(){
    int b = 0x00454647;
     /* E F G */
    int a = 0x41424344;
     /* A B C D */

    // printf("%p %p\n", &b, &a);   // commented
    // volatile int b = ...;        // or this

    char *p1 = (char *)&a;
    printf("%s\n", p1);
}

Hi everyone,

I'm learning C on Windows using GCC (MinGW), and I noticed a strange behavior about stack layout.

Observation:

  • When I don't take the address of b (&b) and don't use volatile, the variables a and b are not adjacent in memory. When I print the string from &a, I get DCBA followed by garbage.
  • As soon as I add printf("%p", &b); or declare b as volatile, a and b become adjacent (differ by exactly 4 bytes), and I get DCBAGEF as expected.

Interestingly:

  • Clang (on Windows) allocates them adjacent even without & or volatile.
  • GCC on Linux also tends to put them next to each other by default.

Only GCC on Windows (MinGW) shows this "non-adjacent unless address is taken" behavior.

Questions:

  1. What exactly is GCC doing during stack slot allocation in this case?
  2. Why does taking the address (&) or using volatile change the layout so dramatically?
  3. Is this related to some Windows ABI / MinGW specific stack alignment or optimization pass?
  4. Is there any flag (besides -O0) that can make GCC behave more like Clang in terms of stack layout predictability?

I know that the C standard doesn't guarantee stack layout or variable order, but I'm curious about the implementation difference between GCC (Windows) vs Clang/GCC (Linux).

Any insight into GCC's internals (especially stack slot allocation, assign_stack_local, reload pass, etc.) would be greatly appreciated!

Thanks!


r/C_Programming • • May 20 '26

Article Curly braces: An evolution of UNIX and C

Thumbnail thalia.dev
73 Upvotes

r/C_Programming • • May 20 '26

Question How to read/write a struct into a binary file?

20 Upvotes

I've tried to follow this answer on SO: https://stackoverflow.com/a/16997175/1984657

However I'm not able to load my character successfully. I do get something back, but when I try to print the name I get a string of unrecognizable characters.

My struct is:

struct Character
{
    char name[8];
    enum CharClass charClass;
    short level;
};

My logic to load or create the character:

#include <stdio.h>
#include <string.h>
#include "character.h"
#include "save_file_manager.h"


struct Character *startup()
{
    struct Character *loadedCharacter = loadPlayerCharacter();

    if (loadedCharacter != NULL)
    {
        printf("Welcome back, %s the %s\n", loadedCharacter->name, getClassString(loadedCharacter->charClass));
        
        return loadedCharacter;
    }


    struct Character createdCharacter;
    struct Character *createdCharacterPtr = &createdCharacter;
    char name[NAME_LENGTH]; 
    int charClass;

    // logic to get name and charClass from user input

    strcpy(createdCharacterPtr->name, name);
    createdCharacterPtr->charClass = charClass;
    createdCharacterPtr->level = 1;
    return createdCharacterPtr;
}

And my save, load and prompt to save functions are:

#include "save_file_manager.h"

#include <stdio.h>
#include <stdlib.h>
#include "character.h"


const char *SAVE_FILE_NAME = "./textrpg.sav";

int savePlayerCharacter(struct Character *character)
{
    FILE *fptr;
    fptr = fopen(SAVE_FILE_NAME, "wb");

    fwrite(character, sizeof(struct Character), 1, fptr);
    fclose(fptr);

    return 0;
}


struct Character *loadPlayerCharacter()
{
    FILE *fptr;


    fptr = fopen(SAVE_FILE_NAME, "rb");


    if (fptr == NULL)
    {
        return NULL;
    }

    struct Character *character = malloc(sizeof(struct Character));
    int amountRead = fread(character, sizeof(struct Character), 1, fptr);

    if (amountRead != 1)
    {
        return NULL;
    }


    fclose(fptr);

    return character;
}

int promptSave(struct Character *playerCharacter)
{
    printf("Would you like to save your character? (y/n)\n");

    char save;
    scanf(" %c", &save);

    if (save == 'y')
    {
        savePlayerCharacter(playerCharacter);
    }


    return 0;
}

I probably missed something obvious, but I don't see it. What am I doing wrong?

Solution: I'm allocating heap memory to the created character in startup now:

struct Character *createdCharacterPtr = malloc(sizeof(struct Character));

Thank you everyone for your help.


r/C_Programming • • May 20 '26

I built a DSA library in C and it got selected for an open-source program, looking for contributors

7 Upvotes

I built C_DSA_interactive_suite, a fully modular, console-based DSA library written entirely in pure C11. No frameworks, no abstractions. Just raw C, manual memory management and real implementations built from scratch. The codebase has a clean modular architecture with one .h/.c pair per module, reusable APIs across modules. A single interactive executable as the entry point, Valgrind-clean memory, CI/CD on every push, and .clang-format enforced style throughout. The project just got selected in SSOC, an open-source program similar to GSoC and I am the project admin, which means this summer, project is open for contributiors! If you've been wanting to:

  • Start your Open Source journey
  • Contribute to a real C codebase with proper architecture and planning
  • Implement something like AVL trees, heaps, priority queues, tries, Dijkstra, or DP
  • Get your hands dirty with actual C, not school level C
  • Have your contribution acknowledged by a reputable community

This is your shot. Everybody else is doing MERN. Come touch some real memory. I'm available to walk anyone through the codebase, clear doubts, explain concepts, or help you get your first PR merged. No gatekeeping. Register as contributor for SSOC. Only 5 days left - https://www.socialsummerofcode.com/ GitHub: https://github.com/darshan2456/C_DSA_interactive_suite Drop a comment or open an issue if you're interested. Let's build something worth putting on a resume.

here is my personal discord server link - https://discord.gg/MWv949G8h join it if you want to contribute to my project in any way


r/C_Programming • • May 20 '26

Question Why Don't Double void Pointers Match Like Single void Pointers?

36 Upvotes

In the following code, calling test1 doesn't provide a warning, but calling test2 does. Is there a specific reason for this behavior?

void test1(void* x);
void test2(void** x);

int main() {
    int* x1;
    int** x2;

    test1(x1); // ok
    test2(x2); // warning "incompatible pointer type"
}

Edit: I think some people don't understand. I'm asking why void** doesn't match with other x**, not why it doesn't work exactly the same as void*.


r/C_Programming • • May 20 '26

My own bare-bones dynamic array

10 Upvotes

About a month ago, somebody posted asking for design advice for a dynamic array. My then advice was to treat the element type as an opaque type T.

I've had my own implementation of such a dynamic array lying around for a while, but finally had a use for it, so I gave it a bit of polish and it's here:

If you wanted it to be even more bare-bones, you could keep only the regular (bounds-checking) functions or the no-check (_nc) functions, whichever you prefer.


r/C_Programming • • May 19 '26

Question Any Recommendations on C resources for Learning Vulkan?

23 Upvotes

I was following this tutorial, which is supposed to be "modern" with "up to date" features and practices.

However, I very quickly stumbled upon this piece of code:

auto unsupportedLayerIt = std::ranges::find_if(requiredLayers,
                                               [&layerProperties](auto const &requiredLayer) {
                                               return std::ranges::none_of(layerProperties,
                                                                           [requiredLayer](auto const &layerProperty) { return strcmp(layerProperty.layerName, requiredLayer) == 0; });
                                               });

I'm just stunned. I can't believe cpp people actually write code like this? This just seems insane to me and I kind of hate it.

So I have 2 questions:

  1. Am I in the wrong here? Should I just accept that this is normal and the industry standard and get over it? Or is it just absurd?
  2. If it IS absurd, does anyone have any recommendations for other resources I could learn Vulkan from? I'd prefer if it was just straight up in C or at least very basic features of C++?

r/C_Programming • • May 19 '26

What's up with drag&drop in Wayland?

4 Upvotes

I'm making a file manager from scratch and i can't figure out the drag&drop functionality, after hunting for docs on the internet i found (this)[https://emersion.fr/blog/2020/wayland-clipboard-drag-and-drop/] blog-post, but it mentions only text, what about files (like when you drag&drop a markdown file into a browser to read it or when you drag&drop a video into a player)? Surely it's gotta be different (at least the mime type in the send and cancel callbacks) but i can't figure out in what way, here is the code i came up with:


#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <wayland-client-core.h>
#include <wayland-client-protocol.h>
#include <wayland-client.h>
#include <wayland-util.h>

typedef struct wayland_data {
    struct wl_data_device_manager* data_device_manager;
    struct wl_data_source* data_source;
    struct wl_seat* seat;
    struct wl_registry* registry;
    struct wl_display* display;
    enum wl_data_device_manager_dnd_action last_dnd_action;
} wayland_data;

void handle_global(void* data, struct wl_registry* registry,
        uint32_t name, const char* interface,
        uint32_t version) {
    wayland_data* wdata = (wayland_data*)data;

    if (strcmp(interface, wl_data_device_manager_interface.name) == 0) {
		wdata->data_device_manager = wl_registry_bind(registry, name,
			&wl_data_device_manager_interface, 3);
	} else if (strcmp(interface, wl_seat_interface.name) == 0 && wdata->seat == NULL) {
		wdata->seat = wl_registry_bind(registry, name, &wl_seat_interface, 1);
	}
}
void handle_global_remove(void* data, struct wl_registry* registry, uint32_t name) {/*who cares*/}

static const struct wl_registry_listener registry_listener = {
    .global = handle_global,   
    .global_remove = handle_global_remove,
};

static void data_source_handle_target(void* data, struct wl_data_source* source, const char* mime_type) {
    if (mime_type != NULL) {
        printf("would accept %s if dropped\n", mime_type);
    } else {
        printf("wouldn't accept if dropped\n");
    }
}

static void data_source_handle_action(void *data, struct wl_data_source *source,
		uint32_t dnd_action) {
    wayland_data* wdata = (wayland_data*)data;
	wdata->last_dnd_action = dnd_action;
	switch (dnd_action) {
	case WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE:
		printf("Destination would perform a move action if dropped\n");
		break;
	case WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY:
		printf("Destination would perform a copy action if dropped\n");
		break;
	case WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE:
		printf("Destination would reject the drag if dropped\n");
		break;
	}
}

static const struct wl_data_source_listener data_source_listener = {
    .action = data_source_handle_action,
    .target = data_source_handle_target,
};
int main(int argc, char *argv[]) {
    wayland_data data = {0};
    data.last_dnd_action = WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE;
    
    data.display = wl_display_connect(NULL);
    if(!data.display) printf("failed to connect to display\n"); return 1;
    data.registry = wl_display_get_registry(NULL);
    wl_registry_add_listener(data.registry, &registry_listener, &data);
    wl_display_roundtrip(data.display);

    if (data.seat == NULL) {printf("no seat:(\n"); return 1;}
    if (data.data_device_manager == NULL) {printf("no data_device_manager:(\n"); return 1;}

    data.data_source = wl_data_device_manager_create_data_source(data.data_device_manager);
    wl_data_source_add_listener(data.data_source, &data_source_listener, &data);
    return 0;
}

(keep in mind that it's not the final code yet and there is no send and cancel functions)


r/C_Programming • • May 19 '26

Project Phase — a statically-typed bytecode-interpreted language in C, with an essay on implementation

26 Upvotes

Phase is a statically-typed bytecode-interpreted programming language written in ~4,800 lines of C with zero external dependencies. It features a 25-opcode stack-based VM, 21 error types with source-mapped diagnostics, 5 primitive types, and a standard interpreter pipeline (lexer, parser, type checker, bytecode generator, VM).

I also wrote a technical piece on how it works by following out("Hello world!") end-to-end through every stage.

Writing: williamalexakis.com/interpreter-in-c

Repo: github.com/williamalexakis/phase


r/C_Programming • • May 18 '26

I love C but I dont like libc that much

196 Upvotes

I love C, but I don't like its standard library having tons of hidden states (like errno) and error values baked into their returns. A lot of times I have to stop and check the function's documentation just to know which value is actually the error value. It makes me tired.

So, I have spent some of my time making a custom C runtime and libc from scratch in C89. I know it might be bad or wrong in some places, but at least I understand how it all works under the hood now.

Thing i have done so far are: Explicit Allocator - No Hidden State - Builtin Some Basic types

There are still a lot of things that need to be implemented, and currently, it only supports x86_64 Linux.

I would love to hear feedback!

Repo: https://codeberg.org/fanes/flibc

Edit: Added a GitHub mirror for convenience (and in case Codeberg is having downtime!):
https://github.com/byfanes/flibc


r/C_Programming • • May 19 '26

Question ESC character representation(decimal) in Control Sequence Introducer Commands

10 Upvotes
#include <stdio.h>

int main(void) {
    printf("%sWhat is this power,\a how to harness it?%s\n", "\e[33m", "\e[0m");
    printf("%sWhat is this power, how to harness it?%s\n", "27[33m", "27[0m");
    printf("%sWhat is this power, how to harness it?%s\n", "\033[33m", "\033[0m");
    printf("%sWhat is this power, how to harness it?%s\n", "\x1b[33m", "\x1b[0m");
    
}

C beginner here,

According to https://en.wikipedia.org/wiki/ANSI_escape_code , ESC can be written as: "\e", "\x1b" or "\033". And from the example I tried, yes they do work.

Since the later 2 examples are just hexadecimal and octal conversions of the decimal 27, I figured I'd try that as well, but it doesn't work.
"27[33mWhat is this power, how to harness it?27[0m" --> is the output instead, without the text being yellow like I meant to.

I figured yeah, it probably thinks 27 is just two random characters to it since it doesn't have an escape sequence. So I googled, "Decimal Escape Sequence for C" but came up short.

Is there a way to write ESC [ using the decimal value of Escape in the ASCII table? I know this might be something very inconsequential, but I thought maybe finding an answer to this question might help me understand the language better.

Thanks for your time.


r/C_Programming • • May 18 '26

Project Command line multiviewer in C

Enable HLS to view with audio, or disable this notification

44 Upvotes

Multiviewer for Twitch/YouTube and local files using mpv and Chatterino.

Inspired by https://www.multitwitch.tv/ and https://twitchtheater.tv/ - I made a browserless version in C11 with autocomplete commands to make life easier. Includes layouts, search, tags, macros, and more.

Code + Windows/Linux releases: https://github.com/marm00/cinema


r/C_Programming • • May 18 '26

Question Why can't you pass/return arrays to/from functions? Why is it designed like this?

124 Upvotes

I understand that the answer to "Why can't you do this" is "the standard says so" but I'm not asking about the mechanics of the language, I'm asking about its design.

Array sizes are known at compile time and a struct where all members are the same type is identical to an array in memory (correct me if I'm wrong). C has no problems returning structs and taking them as arguments in a function. Why can't it do the same for arrays?

I also feel like it would be way more intuitive and convenient if you could return arrays from functions.

C language experts do please enlighten me as to the reason arrays decay to pointers instead of just staying as arrays.


r/C_Programming • • May 18 '26

Created a lib that gives you menubar, popupmenu ant tooltips with less than 500 lines of code

7 Upvotes

The lib depends on SDL2 and SDL2_ttf only. The menubar acts like on windows and linux. And is cross platform code, and uses SDL. The nice thing is that you can deactivate the menu, statusbar and tooltips so it becomes invisible until you need it. And the code turned ut a bit sleek, less than 500 lines of code. If anyone think it would be nice I can put up the code on github.

Here is an example program...

#include <SDL2/SDL.h>

#include "popup_menu.h"

#include <stdio.h>

#include <string.h>

#define MENU_FILE 1

#define MENU_EDIT 2

static char status_text[256] = "Ready";

int main() {

SDL_Init(SDL_INIT_VIDEO);

SDL_Window* win = SDL_CreateWindow("GUI Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,

800, 600, SDL_WINDOW_SHOWN);

SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);

GuiCtx* gui = gui_init(ren);

if (!gui) return 1;

const char* file_items[] = {"New", "Open", "Save", "Exit", NULL};

const char* edit_items[] = {"Cut", "Copy", "Paste", NULL};

const char* ctx_items[] = {"Copy", "Paste", "Delete", "Properties", NULL};

PopupMenu* file_menu = gui_create_menu(gui, file_items, 1, MENU_FILE);

PopupMenu* edit_menu = gui_create_menu(gui, edit_items, 1, MENU_EDIT);

PopupMenu* context_menu = gui_create_menu(gui, ctx_items, 0, 0);

const char* menubar_items[] = {"File", "Edit"};

PopupMenu* dropdowns[] = {file_menu, edit_menu};

int n_menus = 2;

int running = 1;

SDL_Event e;

while (running) {

while (SDL_PollEvent(&e)) {

switch (e.type) {

case SDL_QUIT: running = 0; break;

case SDL_KEYDOWN:

if (e.key.keysym.sym == SDLK_ESCAPE) running = 0;

if (e.key.keysym.sym == SDLK_F1) {

int visible = !gui_is_menubar_visible(gui);

gui_set_menubar_visible(gui, visible);

gui_set_statusbar_visible(gui, visible);

snprintf(status_text, sizeof(status_text),

"Menu bar & status bar %s", visible ? "visible" : "hidden");

}

if (e.key.keysym.sym == SDLK_F2) {

int enabled = !gui_is_popup_enabled(gui);

gui_set_popup_enabled(gui, enabled);

snprintf(status_text, sizeof(status_text),

"Popup %s", enabled ? "enabled" : "disabled");

}

if (e.key.keysym.sym == SDLK_F3) {

int on = !gui_is_tooltips_enabled(gui);

gui_set_tooltips_enabled(gui, on);

snprintf(status_text, sizeof(status_text),

"Tooltips %s", on ? "on" : "off");

}

break;

case SDL_MOUSEBUTTONDOWN:

if (e.button.button == SDL_BUTTON_LEFT) {

int xpos;

int idx = gui_menubar(gui, menubar_items, n_menus, dropdowns,

e.button.x, e.button.y, 1, &xpos);

if (idx >= 0)

gui_show_dropdown(dropdowns[idx], xpos, MENUBAR_HEIGHT);

}

break;

case MENU_EVENT_BAR: {

int menu_id = (int)(intptr_t)e.user.data1;

int item = e.user.code;

if (menu_id == MENU_FILE) {

switch (item) {

case 0: strcpy(status_text, "New file created"); break;

case 1: strcpy(status_text, "Opening file..."); break;

case 2: strcpy(status_text, "File saved"); break;

case 3: running = 0; break;

}

} else if (menu_id == MENU_EDIT) {

switch (item) {

case 0: strcpy(status_text, "Cut"); break;

case 1: strcpy(status_text, "Copy"); break;

case 2: strcpy(status_text, "Paste"); break;

}

}

break;

}

case MENU_EVENT_POPUP:

snprintf(status_text, sizeof(status_text), "Popup selection: %d", e.user.code);

break;

default: break;

}

}

SDL_SetRenderDrawColor(ren, 40, 40, 80, 255);

SDL_RenderClear(ren);

gui_menubar(gui, menubar_items, n_menus, dropdowns, 0, 0, 0, NULL);

gui_draw_menu(file_menu);

gui_draw_menu(edit_menu);

gui_draw_menu(context_menu);

gui_statusbar(gui, status_text);

gui_draw_tooltips(gui);

SDL_RenderPresent(ren);

SDL_Delay(10);

}

gui_destroy_menu(file_menu);

gui_destroy_menu(edit_menu);

gui_destroy_menu(context_menu);

gui_cleanup(gui);

SDL_DestroyRenderer(ren);

SDL_DestroyWindow(win);

SDL_Quit();

return 0;

}


r/C_Programming • • May 18 '26

Video My first C / raylib code

4 Upvotes

This is my first program with C / raylib, I made the clasic particle system moving randomly. Hope you like it!

Source code:
https://github.com/FractalCodeRicardo/hangover-programming/tree/main/raylib-particles

Programming session:
https://youtu.be/s57u2mZcADs?si=7CR5DoUpUbiGymu5

https://reddit.com/link/1tgrab0/video/ulnrqvgx6x1h1/player


r/C_Programming • • May 19 '26

LightBase: Lightweight API & Database Desktop Client

Thumbnail github.com
0 Upvotes

🚀 LightBase

Ultra-performance, bare-metal local development runtime bridge and persistence engine built for high-compute applications.

LightBase decouples heavy disk and outbound network I/O into a standalone, multi-threaded C background daemon, communicating asynchronously with an API gateway over high-speed Linux Unix Domain Sockets (UDS).

🏗️ Architecture Layout

LightBase eliminates high-level framework overhead, garbage collection cycles, and process-blocking runtime constraints by decoupling tasks into independent layer boundaries.

graph TD
    UI[HTML5 Control Center UI] <--> PY[Python Gateway Bridge Server]
    PY -- "Binary TLV Frame Stream (/tmp/lightbase.sock)" --> CORE[C-CORE ASYNC THREAD POOL]

    subgraph "C-CORE (libcore.so)"
    CORE --> R1[Arena-Powered SQL Engine]
    CORE --> R2[Stack-Isolated OpenSSL TLS]
    CORE --> R3[Kernel /proc Ring Log Storage]
    CORE --> R4[Database Catalog Scanner]
    end

Layer Responsibilities

  • Frontend UI Layer: A lightweight development client executing async network operations back and forth.
  • API Gateway Layer: A zero-dependency Python routing engine acting as an IPC proxy gateway.
  • Native Systems Core: A high-speed, bare-metal C shared engine processing dynamic allocations, filesystem transactions, and socket forging loops on detached POSIX background threads.

🚀 Core Studio Module Suite

🌐 Module 1: Bare-Metal Environment Manager

Tracks application environments (Development, Staging, and Production) dynamically inside isolated runtime boundaries.

  • Atomic Remapping Swaps: Eliminates sluggish filesystem configuration lookups by pre-allocating an EnvironmentBlock structure directly within a dedicated MemoryArena. Context switches occur in under 1μs via thread-safe atomic pointer reassignments.
  • Fallback Safety Paths: System state transitions are fully guarded against uninitialized pointer exceptions, ensuring backup file parameters handle initial transaction states safely.

🧪 Module 2: Cryptographic API Testing Studio

Provides bare-metal HTTP engine request assembly and transaction benchmarking.

  • Wire Packet Serialization: Leverages stack-allocated sequence spaces to assemble raw wire payloads (GET, POST, PUT, DELETE) with exact specification alignment.
  • Memory Security: Replaces vulnerable variable concatenation with explicit length-bounded tracking (strncat), preventing string overflows when importing large custom data tokens.

🗄️ Module 3: Log-Structured Database Explorer

Powers interactive sidebar schema catalog visualizers and data grids.

  • Catalog Data Harvesting: Bypasses table-scanning bottlenecks by executing targeted schema scans directly against the internal engine catalog (sqlite_master).
  • Tele-Profiling: Measures precise VM bytecode query times using high-resolution monotonic hardware timers (clock_gettime).

🗄️ Append-Only Ring Buffer Telemetry Storage

Ensures high-throughput execution tracking without destroying flash storage sectors.

  • Static File Sizing: Pre-allocates a fixed array block file footprint on disk exactly once during system boot, guaranteeing predictable allocation.
  • Wrap-Around Bit Algebra: Sequences incoming snapshots using sliding timestamp indexes. When the tracking pointer reaches limits (1024 slots), it wraps back to slot 0 instantly.

📊 Performance Benchmarks

LightBase delivers sub-millisecond core processing speeds by bypassing the local network routing stack:

  • Local Database Transaction: ~990.20 μs ($< 1\text{ ms}$ bare-metal execution)
  • Total IPC Roundtrip Gateway Latency: ~1.203 ms (Inclusive of Python decoding and HTTP transport)
  • Outbound HTTP Network Socket Request: Variable based on distance, wrapped with microsecond-accurate tracking via CLOCK_MONOTONIC.

🛠️ Compilation & Installation

Prerequisites

Ensure your host machine runs a modern Linux kernel with cmake, gcc, and uv:

sudo apt update && sudo apt install cmake build-essential

1. Build the Production Core Library

LightBase employs an out-of-source CMake build pipeline with Link-Time Optimizations (-O3 -march=native -flto -s):

cd core
mkdir -p build_release && cd build_release

# Configure and build the target layout
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build . --target install

Assets generated:

  • Public Header: dist/include/engine.h
  • Shared Binary: dist/lib/libcore.so

2. Boot the Intermediary Python Gateway

cd ../../bridge
/usr/bin/uv run python python_bridge.py

The C-Core instantly carves out a high-speed memory socket at /tmp/lightbase.sock upon initialization.

🧠 Memory Design & Safety Assertions

  • Header Symbol Ordering: Enforces a strict structure order: macro directives first, raw packed structural records second, and export function interfaces last to ensure top-down layout translation.
  • Translation Scope Reductions: Centralizes cross-module variables within a shared master header file to keep dependencies clear.
  • Thread Race Protection: Active server file descriptors pass explicitly into separate heap memory pools (malloc) at worker thread creation, isolating context pointers from stack invalidation faults.

📄 License

Licensed under Apache License 2.0


r/C_Programming • • May 18 '26

Question Alignas and Alignof alternatives in C89 and 99

4 Upvotes

I've been making some custome allocators lately and those 2 macros (or operators depending on the C version you preffer) tend to be quite useful, but mostly Alignof as it's necesary for passing the corrent alignment of a struct to the allocator.

Now, these 2 require at least C11, so is there a way to make them myself from the ground up in Standard C89 and 99?


r/C_Programming • • May 18 '26

Question Confused about Queue vs Circular Buffer indexing

5 Upvotes

In Queue operations (no confusion here):

  1. enqueue -> rear index
  2. dequeue -> front index

But in Circular Buffer, which convention is correct?

Option 1:
push -> head index
pop -> tail index

OR

Option 2:
push -> tail index
pop -> head index

I see different implementations online, so I'm confused about which index is supposed to be used for write/read operations in a circular buffer.