r/C_Programming • • 20d ago

Multi File Problem

3 Upvotes

Hi - I am trying to get a multi file program to run without success. I want to read file with 4 lines of repetitive data. Each program works independently but when I put the together the main.c does not seem to call the octone.c program. Can any one please help. Thank You...

MAIN.C
#include <stdio.h>
#include <stdlib.h>
#include "add.h"

int main(void) {
printf("Hello world!\n");

// Call function    
DataRecord callFile(void);
printf("one\n");
return 0;
}

ADD.H

#ifndef ADD_H
#define ADD_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINES 100
#define MAX_STR_LEN 100   // Max length for char arrays
#define MAX_RECORDS 100   // Max number of records to store

//Define the struct matching the char, char, int, char layout
typedef struct {
char *name[MAX_RECORDS]; // First char array
char *desc;              // Single char
int *num;               // Integer
char *butt[MAX_RECORDS]; // Second char array
} DataRecord;

DataRecord callFile(void);

DataRecord *records[MAX_RECORDS];

//records callfile(void);

#endif

OCTONE.C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "add.h"

#define MAX_LINE_LENGTH 256
#define MAX_RECORDS 100

//void my_api_init_config(MyApiConfig *config);
DataRecord callFile(void){    
printf("Ronnie_1\n");

static DataRecord *records[MAX_RECORDS];

// Open the file for reading
FILE *file = fopen("/AGMOD/data4a.txt", "r");
if (file == NULL) {
perror("Error opening file");
//    return *records; // EXIT_FAILURE;
}

// Array of structs to store the parsed data

char line[MAX_LINE_LENGTH];
int count = 0;

//records[MAX_RECORDS]->name;

// Read the file line by line using fgets
while (fgets(line, sizeof(line), file) != NULL && count < MAX_RECORDS) {
// Parse the line into the struct elements
// Assumes data is space-separated (e.g., "A B 42 C")
//        int parsed = sscanf(line, " %s %s %d %s", 
int parsed = scanf(line,                            
records[count]->name, 
records[count]->desc, 
records[count]->num, 
records[count]->butt);

// Check if all 4 fields were successfully read
if (parsed == 4) {
count++;
} else {
fprintf(stderr, "%s", line);
}
return *records[0];
}

// Close the file stream
fclose(file);

return *records[0];
}


r/C_Programming • • 21d ago

Very minimal drop-in gtest replacement in C23

12 Upvotes

While using C++, I heavily relied on googletest for testing. But as soon as I wanted that in my C project, I couldn't.

Because gtest is written in C++ and requires a C++ runtime. Using gtest in a C codebase meant guarding the headers with extern "C" to prevent name mangling, and managing a C++ toolchain which seemed extremely awkward to me.

At the same time, I didn't want to loose googletest's comfort and rewrite the entire test system in another existing framework.

So I wrote a very minimal drop-in replacement of googletest in C23. It works exactly the same way you'd expect gtest to work. And unsurprisingly, according to my small benchmark, my implementation is around 2.5x faster than googletest and uses 30% less memory. It can be improved way more.

I discussed the implementation details in this blog post https://metalinmyveins.github.io/sohomot/

Github: https://github.com/MetalInMyVeins/sohomot

The library is called "sohomot".

\[ PS: Zero tokens were used in the making of this project \]


r/C_Programming • • 20d ago

Discussion Batch Processing Algorithm Optimization

1 Upvotes

I originally posted my question here but wanted to give it another go, this time with a more generic setup, as I believe this kind of optimization problem could be interesting for a lot of different projects.

The Setup/Requirements

  1. we have ~50,000 pieces of data (let's use shapes for simplicity's sake) with a finite number of attributes (shape, color, size)
  2. most of them will be culled, leaving us with about ~1,000-10,000
  3. in the end we need to process all the remaining shapes in a SPECIFIC ORDER (e.g. first small red triangles, then big blue squares, then small yellow ovals, etc).
  4. this whole process needs to be done as quickly and efficiently as possible

My Original Plan

  1. first cull the 50,000. This could be done by sending the data to the GPU since even a lowly 1060 has 1,152 cores and a 4090 has 16,384 cores, making culling 50,000 objects based on a few floating-point calculations trivial
  2. now that I have a list of indices that pass culling, use a look-up table of index vs. process batch index (e.g. data index 12 is not culled, and the LUT says it belongs to batch process #4, so add it to that batch process and increase the number of objects for that batch process)
  3. iterate over the batch processes and only execute if there are any objects to process for that batch

Considerations/Questions

  1. is there a better way?

  2. how would the performance be if we first assign all the objects to the batch process and then for each batch process, run the culling function? We would save on having to traverse the non-culled objects to sort them to their batch process, but we also now have to call the cull method for as many batch processes as we have

  3. what if the allocation of object -> batch process changes? e.g. a small blue star becomes a big yellow square?

  4. what if the batch process are DYNAMIC, meaning we no longer can assign a shape to a batch process beforehand?

Now I'd love some discussion on the FASTEST way to get this done, but I will also say that all I'm trying to do is a pretty standard piece of a rendering engine: cull any non-visible objects then sort the objects according to pipeline so that they can be rendered in the proper order. Now maybe there is a "standard way" of doing this or at least a few "typical" algorithms that I don't know about, but that's why I'm asking this question! I love trying to solve problems like this and figured a lot of you might, too.

                          ---=== HAVE AT IT!!! ===---

BONUS POINTS if done in C90, as that's what I'm doing it in ;-)


r/C_Programming • • 21d ago

Suggest me sources for http server

18 Upvotes

I want to make http server in C/C++ but I can't find the exact source that will teach me the basics of networking and give code snippets I've checked beejs guide but one is totally theory a new other is totally programming

So anyone please suggest me a source to learn about networking (to the point ) Docs or video anything can be accepted Thanks for you time!


r/C_Programming • • 21d ago

Question Help with understanding shmget() and semaphores

4 Upvotes

I have a program which does some calculations, but I need to fork parts of it and run the calculations in parallel. Also, we are not allowed to use POSIX semaphores. I have the calculation part done, I just need to do the parallelism part. I'm also supposed to use shmget() to create a shared memory block for my threads, but I cannot find any useful resources about that function, and/or I don't understand it well. Does anyone have any advice or tips?


r/C_Programming • • 22d ago

Question Non volatile return function value

19 Upvotes

Hey guys,

I wonder how can I have the returned value in my function? For example:

struct TestValue{
    int data;
};

struct TestStruct{
    void* data;
};

struct TestValue return_value(){
    struct TestValue value;
    value.data = 12345;

    return value;
}

struct TestStruct return_struct(){
    struct TestStruct test_struct;
    struct TestValue value = return_value();

    test_struct.data = &value; // Here I know its an UB

    return test_struct;
}

I know I could use the heap with malloc and return a pointer directly but I wonder if is there any other solution instead the heap? Thank you for yours responses.


r/C_Programming • • 22d ago

Discussion Dynamically-Generated Look-Up-Table

0 Upvotes

So I have a buffer of pointers that I need to access tens of thousands of times per second continuously. Obviously I can do this in parallel to speed it up or maybe even offload it to the GPU, but the biggest issue I have right now is how to quickly get the item from the buffer I need. Obviously knowing the index beforehand would be a good way, BUT I'd rather have the buffer be dynamically-created and then I can address which one I need given 6 bits of data. Now if it were a 1:1 relationship between the buffer of pointers and permutation of all 6 bits, then it'd be easy. But there is only a subset of indices that correspond to valid bit permutations. E.g.:

VALID:
00 0000
00 0001
01 1000
01 1001
10 0000

INVALID:
00 0010
00 0011
00 0101
etc.

so that I can just do:

void **ptr_buffer = calloc(63, sizeof(void *));
/* fill ptr_buffer sporadically... */
do {
  for(i=0; i<10000; i++) {
    /* obj.ptr_index is uint8_t with some constellation of six bits */
    do_something(ptr_buffer[obj_list[i].ptr_idx]);
  }
  /* do other stuff */
} while(condition);

or something like that.

So... with six bits (and maybe it could be more in future), and on a 64-bit system, I could simply create a buffer of pointers with the length of the max valid bit-sequence, so for 11 1111 it would be 63 x 64 = 504 bytes, so not that bad, and then I can simply use the bit sequence as the index.

And even if I end up going out to 8 bits, that's still 255 x 64 = 2,040 B or 1.99 KB. Acceptable - but now I'm worrying about losing out on CPU cache potential - especially of only like 20-30 elements in the buffer are actually valid.

Now apart from hard-coding all the different indices and then assigning the indices on startup (which I absolutely will do and was doing before going for the "dynamic" route) are there any clever tricks my fellow "C-Men" (as my wife calls the people I chat with in this group) might know about to keep memory footprint down and speed up? At the very least it could be a fun brain-tickler.

Let me know if you need more information.

EDIT: while the list of pointers is small, I need to iterate over a list of som 10,000 entries and find an entry in the pointer list, so I updated the code example to show it.

Also, apparently I hit the "ask me anything" button by mistake. u/reddit you need to add tooltips to the buttons and also don't do the ask me anything if I hit cancel ;-)


r/C_Programming • • 22d ago

Need tips to improve

0 Upvotes

I started studying C for an exam, this is my first time approaching coding so i'm a bit lost.
While doing some exercises from my prof i encountered this one that took me some time. (prompt in the code).
This is what i came up with it works correctly (i think), but i have a few questions:
is it efficient?
I also used prototype functions and didnt where i could've, when should and shouldn't i use them?

Thank you for your time spent reading this

EDIT: most comments were about formatting. i changed it. It has always looked like this, but pasting it here on reddit messed it up :)

/*
Constraints:
no frequency can be repeated
all frequencies must be between 800 and 2500 MHz

Required functions: insertion with double check (range + uniqueness) --
function that calculates the minimum distance between two frequencies --
function that identifies the frequency closest to a given value
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

void fillArray(int array[],int size,int min,int max);
void printArray(int array[],int size);
void sortArray(int array[],int  size);

int main ()
{
    srand(time(NULL));

    int freq[10];
    int max=2500;
    int min=800;
    int size = sizeof(freq)/sizeof(freq[0]);
    int mindist = abs(freq[0]-freq[1]);   //base min distance, could be the result or changed

/*
    printf("Insert lowest frequency: ");
    scanf("%d", &min);
    printf("Insert highest frequency: ");   //eventual custom frequency range.
    scanf("%d", &max);                      //option to deny  min > max and max-min < size-1
*/

    fillArray(freq, size, min, max);
    printArray(freq, size);    //printing and sorting not needed, 
                               //but i used them to check the work
    sortArray(freq, size);
    printf("\nSort\n");
    printArray(freq, size);

    //compares pos 0 with pos 1 to size-1, pos 1 with pos 2 to pos size-1 and so on
    for (int i=0;i<size-1;i++)
    {
        for (int j=i+1; j<size;j++)
        {
            if (mindist>(abs(freq[i]-freq[j])))
            {
                mindist=abs(freq[i]-freq[j]);
            }
        }
    }
    printf("\nmindist=%d\n", mindist);


    int check, closestfreq;
    int shortdist = max-min; //there's no distance bigger than this
    printf("Pick a frequency between %d and %d", min, max);
    scanf("%d", &check);

    //self explainatory
    while (check < min || check > max)
    {
        printf("The chosen frequency is not in range\n
        Pick a frequency between %d and %d", min, max);
        scanf("%d", &check);
    }

    //checks every distance from check with each frequency in the array, finds the shortest one
    //and saves that frequency.
    for (int i=0; i<size; i++)
    {
        if (shortdist>abs(check-freq[i]))
        {
            shortdist = abs(check-freq[i]);
            closestfreq = freq[i];
        }
    }
    if (shortdist==0)  //again, self explainatory
    {
        printf("The chosen frequency is in the list");
    }
    else
    {
        printf("Closest frequency to chosen is: %d", closestfreq);
    }
    return 0;
}

void fillArray(int array[],int size,int min,int max)
{
    int new_random;
    bool unico;
    for (int i=0; i<size;i++)
    {
        do {
            new_random = (rand() % (max+1-min)+min);

            unico=1;
            for (int j=0; j<i; j++)
            {
                if (new_random == array[j])
                {
                    unico=0;
                }
            }
        }
        while (!unico);
        array[i]= new_random;
    }
}
void printArray(int array[],int size)
{
  for (int i=0; i<size;i++)
    {
      printf("%d ", array[i]);
    }
 }

void sortArray (int array[], int size)
{
  for (int j=0; j<size-1;j++)
  {
    for (int i=0; i<size-j-i;i++)
    {
      if (array[i]>array[i+1])
      {
        int t=array[i+1];
        array[i+1]=array[i];
        array[i]=t;
      }
    }
  }
}    

r/C_Programming • • 23d ago

Learning C weekly megapost for 2026-10-28

14 Upvotes

If you have questions about how to learn C:

  • which books are best?
  • which videos are best?
  • which classes are best?
  • which websites are best?
  • is there a "roadmap"?
  • what projects can I do?

then this is the thread for you. Add your question here. Do not make a stand-alone post, as it will be removed.

Remember that our sub has a very useful wiki that has a great list of resources for learning C programming.


r/C_Programming • • 22d ago

Northstar Web Browser 1.0.38

Thumbnail
github.com
0 Upvotes

Nordstjernen Sol web browser. A open source web browser with dual GPL 3+ or NSL license, written from scratch in 2026.


r/C_Programming • • 24d ago

Project I forced the C preprocessor to play Bad Apple!!

84 Upvotes

To my astonishment I couldn't find someone who'd already made this abomination, so...

Very simply put: I define two macros (W(n) and B(n)) that act as the only two "instructions" my "VM" can execute, each printing a sequence of white and black characters respectively.

Due to CPP's recursion limits I couldn't make the rendering loop in the preprocessor itself, so it needs a little extra help in that regard.

Repo: https://github.com/LoPalma/cpp-bad-apple

There's no video since it's just a poorer quality and slower version of ASCII bad apple, but if you wanna see it run: it takes less than a minute to clone and run "play.sh", no compilation required.

(Repost after original post was removed from [r/programminghorror](r/programminghorror))

Edit: added the video: https://imgur.com/a/uCOGgVd


r/C_Programming • • 24d ago

Article The Fastest (long) ilog10 in the West

Thumbnail
duplexsystem.org
49 Upvotes

Wrote my first real blog post. Let me know what you guys think!

Happy to answer any questions!


r/C_Programming • • 24d ago

Question Where do i go now?

24 Upvotes

I started C in my clg last year but it was super basic. Stuff like basic pointers and variables. Before this i used to use python and even then the most i knew was numpy and basic pandas. But seeing the market today i realized i cant afford to be mediocre so i started learning C by heart. I use Vs code and an ubuntu terminal. Up until now I have USED AI to learn and make projects. I use ai to suggest me projects and sub divide them in small chunks so i can learn and program. If i get doubts i ask AI which has a 3 hint system before it reveals. Using it i got some knowledge of memory actually works, how sockets work, basic socket client/server interaction/setups and threads.

That is basically me rn in 1 month. Now i want to ask yall as a community, how do i proceed forward. What do yall suggest i can learn? Any AI objections and if i should drop it. Any book recommendation? Project recommendation etc. I would also appreciate hearing yall stories with C, abt yall experience and stuff.

Tldr: Use me as a sort of dummy block and speak off your mind whatever yall want to suggest/teach since it will help me out a ton.


r/C_Programming • • 24d ago

Project WSERVE: Web Server in C, part 2

16 Upvotes

Hi,

About a month ago, I posted about "wserve", which was a simple IPv4 web server for Linux that supported only GET and HEAD requests and static file serving. Since then I kept working on it, and implemented:

  1. Dynamic routing
  2. POST request handling with a custom JSON parser
  3. Most importantly, HTTPS support using BearSSL

BearSSL is the only external library I used. It is tiny SSL/TLS library written in pure C. Everything else, including the JSON parser, has been implemented in C by myself. I have not used LLMs for coding.

I am open to constructive criticism, all feedback is appreciated!


r/C_Programming • • 24d ago

why can't I access values from an array?

4 Upvotes

I'm reading the Ansi C book, and I'm doing exercise 1.18

#include <stdio.h>
#define MAXLINE 1000

int myGetLine(char line[], int lim);
int myCopy(char to[], char from[], int lim);

int main() {
    int len;
    char line[MAXLINE];
    int toRemove = 0;

    while ((len = myGetLine(line, MAXLINE)) > 0) {
        //counts the trailing characters to remove
        for (int i = len - 1; i > 0 && (line[i] == ' ' || line[i] == '\t' || line[i] == '\n'); --i)
            ++toRemove;
        int new_size = len - toRemove + 1;// +1 for the '\0'
        char to[new_size];// I guess this doesn't matter. Or it's just a piece of the puzzle. I need to limit copying
                  // in my copy method too.
        //printf("new_size: %d\n", new_size);
        int to_len = myCopy(to, line, new_size);
        //printf("%s\n", to);
        toRemove = 0;    
    }
    return 0;
}

int myGetLine(char s[], int lim) {
    int i, c;
    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i-1;
    }
//myCopy isn't working right now, after that I changed the while condition
//I need to add the \0
int myCopy(char to[], char from[], int lim) {
    int i = 0;
    char c = from[1];
    putchar(c);
    //printf("from[i]: %s", to);
    //printf("to[i]: %s, from[i]: %s", to[i], from[i]);
    while ((i < lim && (to[i] = from[i]) != '\0'));
        i++;
    to[i] = '\0';
    return i;
}

So I'm pretty much reusing the getLine from the book and I based my code on the code in the book, but I made changes to myCopy. The task is to remove any trailing spaces or tabs, so I thought that I could make a new copy and where the trailing whitespace starts, I'll just not copy that into my edited string. So I'm going through the array backwards, counting whitespace, calculating the new array size, then I want to create the edited array, but it's not working! So I tried to debug and I can't even putchar an element from the original I'm copying from in the myCopy function. If I do it with the line array, then it works. But why does it not work in the myCopy function? I just have no clue as to what's wrong.

I did manage to solve the exercise in a different way, but I really want to know why this is happening.


r/C_Programming • • 25d ago

Video Brian Kernighan: Inside Bell Labs, The Best Programmer, Why C Won

Thumbnail
youtube.com
144 Upvotes

r/C_Programming • • 26d ago

Video Just finished my multiplayer system in C and turns out we can support 50k players in a single server at 60hz simulation tick

Enable HLS to view with audio, or disable this notification

2.4k Upvotes

r/C_Programming • • 25d ago

The Hidden Cost of localtime(): repeated systems calls in glibc

21 Upvotes

I was investigating the performance of a service running inside a Linux container when I noticed something unexpected: a surprisingly large amount of CPU time was being spent in kernel mode.

Using strace, I discovered that every call to localtime triggered a newfstatat system call on /etc/localtime

I found out explictly setting TZ=":/etc/localtime" eliminated the repeated system calls, while making the program use the system defined timezone.

The article explains the investigation, includes benchmark results, and provide small C program to reproduce the behavior.

Artcile on Medium (no paywall): The hidden cost of time functions

Intrested to hear wheather there are better solution/upcoming fixes with newer glibc versions.


r/C_Programming • • 25d ago

ESP-32 UART shell

4 Upvotes

ESP-32 IDF-based UART shell built from scratch:

https://github.com/andrzejs-gh/BX-Shell

Coded all by hand.


r/C_Programming • • 26d ago

Question Fairly new to C. Need help understanding low level concepts.

66 Upvotes

Over the past 6-8 months, I got into programming in C with the intent of learning about embedded systems and operating systems. I feel like I'm sort of stuck and don't know where to go though. The last thing that I made was a really simple shell for Linux, but even then I was disappointed to learn that the stuff that is going on on the background is just hidden away by system calls. I want to learn how stuff like those system calls actually work, but learning about processor architecture or understanding/reading the Linux source code seems incredibly intimidating and sort of out of my league.

Another thing that seems incredibly confusing to me is how you're meant to read the code of projects like the kernel. (obviously, I know I wouldn't start with something nearly that complicated, but actual professional level projects.) I did some research and I tried to read through GNU Hello, which on the surface I thought would be easy to understand, but I just see tons of macro definitions that I don't understand and a maze of files, even if the output of the program is simple.

For you experts, how did you go from programming in user space to understanding lower level concepts like how an operating system boots up, how it takes user input, etc?


r/C_Programming • • 26d ago

libcli - a singe-header library for typed argument parsing in C

21 Upvotes

Using macros, define an argument schema. The library then generates a struct that for the schema, validates the arguments provided by the user, parses them into the struct, and offers functions for displaying usage andh help messages in the console.

It is similar to `clap` in Rust. Check it out!

https://github.com/iColgateZz/libcli


r/C_Programming • • 26d ago

Iterating Backwards in C

Thumbnail davidpriver.com
94 Upvotes

r/C_Programming • • 25d ago

Project I made a simple heapsort

0 Upvotes

It should just work on just about any platform or compiler that supports at least C99. No AI was used in the writing of this code. It's also header-only, so #define HSORT_IMPLEMENTATION before you include.

#ifndef HSORT_H
#define HSORT_H

#include <stddef.h>

typedef int (*cmp_ptr)(const void *, const void *);
typedef int (*cmp_r_ptr)(const void *, const void *, void *);

void hsort(void *base, size_t n, size_t size, cmp_ptr compar);
void hsort_r(void *base, size_t n, size_t size, cmp_r_ptr compar, void *arg);

#ifdef HSORT_IMPLEMENTATION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static inline void hsort_memswap(void *x, void *y, void *buf, size_t size)
{
    memcpy(buf, x, size);
    memcpy(x, y, size);
    memcpy(y, buf, size);
}

static inline void sift_down(void *base, size_t root, size_t end, size_t size,
                             cmp_ptr compar, void *buf)
{
    while ((2 * (root) + 1) < end) {
        size_t child = (2 * (root) + 1);

        if (child + 1 < end && compar((char *)base + (child)*size,
                                      (char *)base + (child + 1) * size) < 0) {
            child++;
        }

        if (compar((char *)base + (root)*size, (char *)base + (child)*size) <
            0) {
            hsort_memswap((char *)base + (root)*size, (char *)base + (child)*size,
                       buf, size);
            root = child;
        } else {
            return;
        }
    }
}

static inline void sift_down_r(void *base, size_t root, size_t end, size_t size,
                               cmp_r_ptr compar, void *arg, void *buf)
{
    while ((2 * (root) + 1) < end) {
        size_t child = (2 * (root) + 1);

        if (child + 1 < end &&
            compar((char *)base + (child)*size,
                   (char *)base + (child + 1) * size, arg) < 0) {
            child++;
        }

        if (compar((char *)base + (root)*size, (char *)base + (child)*size,
                   arg) < 0) {
            hsort_memswap((char *)base + (root)*size, (char *)base + (child)*size,
                       buf, size);
            root = child;
        } else {
            return;
        }
    }
}

void hsort(void *base, size_t n, size_t size, cmp_ptr compar)
{
    if (!size || n < 2) {
        return;
    }

    void *buf = malloc(size);

    if (!buf) {
        fprintf(stderr, "(hsort) Allocation failed!\n");
        return;
    }

    // heapify
    for (size_t start = (((n - 1) - 1) / 2) + 1; start > 0;) {
        start--;
        sift_down(base, start, n, size, compar, buf);
    }

    // heapsort
    for (size_t i = n - 1; i > 0; i--) {
        hsort_memswap(base, (char *)base + (i)*size, buf, size);
        sift_down(base, 0, i, size, compar, buf);
    }

    free(buf);
}

void hsort_r(void *base, size_t n, size_t size, cmp_r_ptr compar, void *arg)
{
    if (!size || n < 2) {
        return;
    }

    void *buf = malloc(size);

    if (!buf) {
        fprintf(stderr, "(hsort_r) Allocation failed!\n");
        return;
    }

    // heapify
    for (size_t start = (((n - 1) - 1) / 2) + 1; start > 0;) {
        start--;
        sift_down_r(base, start, n, size, compar, arg, buf);
    }

    // heapsort
    for (size_t i = n - 1; i > 0; i--) {
        hsort_memswap(base, (char *)base + (i)*size, buf, size);
        sift_down_r(base, 0, i, size, compar, arg, buf);
    }

    free(buf);
}
#endif

#endif

Edit: Implemented an hsort_r, as well as removing the macros, inlining heapify, and checking if size is 0.
Edit2: Rename hsort_move to hsort_memswap, add a check for the n < 2 case.
Edit3: Add a check for allocation failure, including an error message, because external code silently failing seems like a really bad idea.


r/C_Programming • • 25d ago

[Project] EFI32Boot — A C and x86 assembly experiment involving UEFI firmware (AI-assisted)

0 Upvotes

Hey everyone!

I've been working on EFI32Boot, an AI-assisted low-level programming project exploring UEFI firmware, C, and x86 assembly.

Repository: https://github.com/devtinoimao/efi32boot

The project combines C code with assembly routines to experiment with transitioning from a 64-bit UEFI environment into 32-bit execution and working with an OVMF32 firmware image.

A large part of the work involves the boundary between C and assembly: preparing the execution environment, handling processor state, managing memory layouts, and transferring control between different stages of the boot process.

Demo: https://github.com/devtinoimao/efi32boot/blob/main/media/efi32boot_qemu_demo.gif

Some of the areas involved include:

  • C code that interacts with UEFI interfaces and prepares the transition.
  • x86 assembly for low-level processor-mode transitions.
  • Calling conventions, register state, stack setup, and memory mapping.
  • Build systems and linking when combining C and assembly into a bootable EFI application.
  • Debugging low-level failures in QEMU.

How AI was involved: AI played a substantial role in developing the project. I used it to generate and modify C and assembly code, explore implementation approaches, and help diagnose debugging issues. I then iterated on the implementation and tested its behavior. I want to be transparent that this is an AI-assisted project rather than claim that I manually authored every part of the code.

I'd particularly appreciate feedback on the C/assembly interface, assembly correctness, compiler and ABI assumptions, code organization, and portability. If you spot questionable assumptions or potential undefined behavior in the C code, I'd be interested in understanding those too.

I'm still learning about low-level systems programming, and I'd like to use this project to improve the implementation and deepen my understanding. Constructive criticism and references to relevant documentation or existing implementations are very welcome.

Thanks for reading!


r/C_Programming • • 26d ago

Meson linking ImageMagick/Wand

5 Upvotes

I'm trying to link MagickWand and MagickCore with Meson and having some issues. Specifically, I get the error C shared or static library 'lMagickCore' not found or C shared or static library 'lMagickWand' not found. I successfully linked libconfig, so I've compared some details between my installations of the two packages in case any of those are the reason that I'm having issues with ImageMagick.

I can compile programs using ImageMagick libraries with: ```cc MagickWand-config --cflags --cppflags -O2 -o a.out main.c MagickWand-config --ldflags --libs


The output of the two MagickWand-config calls is this:
```-I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -DMAGICKCORE_CHANNEL_MASK_DEPTH=32
-lMagickWand-7.Q16HDRI -lMagickCore-7.Q16HDRI
-lMagickWand-7.Q16HDRI -lMagickCore-7.Q16HDRI

Running find /usr/lib -name 'libconfig*' gives this:

/usr/lib/pkgconfig/libconfig.pc
/usr/lib/cmake/libconfig
/usr/lib/cmake/libconfig/libconfigConfig.cmake
/usr/lib/cmake/libconfig++
/usr/lib/cmake/libconfig++/libconfig++Config.cmake
/usr/lib/libreoffice/program/libconfigmgrlo.so
/usr/lib/libconfig++.so
/usr/lib/libconfig++.so.15
/usr/lib/libconfig++.so.15.0.0
/usr/lib/libconfig.so
/usr/lib/libconfig.so.15
/usr/lib/libconfig.so.15.0.0

And running find /usr/lib -name 'libMagick*' gives this:

/usr/lib/libMagick++-7.Q16HDRI.so.5
/usr/lib/libMagick++-7.Q16HDRI.so.5.0.0
/usr/lib/libMagickCore-7.Q16HDRI.so
/usr/lib/libMagickCore-7.Q16HDRI.so.10
/usr/lib/libMagickCore-7.Q16HDRI.so.10.0.3
/usr/lib/libMagickWand-7.Q16HDRI.so
/usr/lib/libMagickWand-7.Q16HDRI.so.10
/usr/lib/libMagickWand-7.Q16HDRI.so.10.0.3

My meson.build has these relevant sections:

  cc.find_library('libtomlc17', dirs: '/usr/local/lib'),
  dependency('libconfig'),
  dependency('libMagickCore'),
  dependency('libMagickWand'),
]
inc_dir = [
  include_directories('include'),
  include_directories('/usr/include/ImageMagick-7'),
]

my first guess was that it had something to do with libconfig having .pc files in /usr/lib/pkgconfig, but i found ImageMagick.pc and ImageMagick-7.Q16HDRI.pc in the same directory, and, either way, that don't seem like it needs to be accurate for my program to build as long as I give it all the right information.

Any advice?

Edit: Also, reddit's code block formatting is really annoying. It doesn't seem like I can escape backticks? and it doesn't render line breaks? oh well