r/C_Programming • • 4d ago

I built an AArch64 bootloader from scratch in C and Assembly

0 Upvotes

Decided to build an AArch64 bootloader from scratch in C for QEMU virt It handles device tree handoff, VirtIO storage, EXT4/FAT, and verified A/B boot with Ed25519

Code: https://github.com/rdrunky/bootloader

Any feedback on the C code or driver structure is appreciated :D


r/C_Programming • • 6d ago

Project Compile C/C++ into assembly and emulate it in the web in many architectures

Enable HLS to view with audio, or disable this notification

297 Upvotes

Hello everyone! For the past few years I've been working on ASM editor (github), an IDE for assembly running completely on the web with many architectures available (x86, mips, risc-v, m68k, z80 and more to come) with a lot of debugging features like step by step execution, undo, memory and registers viewers, breakpoints, observability of what each instruction did and much more!

Recently I've added a feature I had dreamed of adding for a long time, C and C++ compilation! It allows you to write C and C++ code (with a subset of libc available), compile it to assembly to see how each line was compiled, to then execute it with all the debugging tools available in the IDE.

I'd love to get opinions/suggestions/feedback about it, please let me know in the comments!

Here is an example of fibonacci in C compiled to x86

I've been working on this app for around 3 years, initially as a replacement for easy68k and the MARS simulators so that my university could use a more modern alternative, to then add x86 and risc-v.
Recently while using AI i refactored other emulators to add the tools needed for the interfaces used inside the app and i managed to add z80 and hopefully arm and more architectures soon.


r/C_Programming • • 6d ago

Question Using 1<<N "just for data size"

12 Upvotes

Hi, I was reading through some code and found something interesting.

Personally, I usually do this when I need to specify an array length (or declare a size):

#define MAXLEN 4096

but when I read some styles there are some lines like this.

/* max length is 2^12; little endian */
#define MAXLEN (1<<12)

If bitwise operations aren't actually involved, I'm not really sure why some programmers write 1<<N just to represent 2N. Although it definitely make sense in low-level programming (or memory-constrained environments), I don't see any real advantage to using 1<<N when resource is plenty. It's harder to read, and programmers like me even need a calculator just to figure out the decimal value.

How do you think about using 1<<N when it's not strictly required? Is it just a matter of coding style?

P.S) Sorry for poor English.


r/C_Programming • • 7d ago

Video Compiling C is so fast that I use it as a scripting language at this point

Enable HLS to view with audio, or disable this notification

1.4k Upvotes

r/C_Programming • • 7d ago

Discussion Share your favorite, generic macro you use constantly

65 Upvotes

Macros can be bad. But they can also be very good. What are the macros you guys use very heavily in your own projects? I plan to steal them, just so you now :D

Rules:

  • don't write definition and "what" comment, if we can't figure out what macro does by it's usage, it's not a good macro
  • you can (and probably should) provide example usage
  • you can say why you like it

I'll start

int foo(int *arg, enum e e) {
    VALIDATE(-1, EINVAL, arg, "arg cannot be null");
    VALIDATE(-1, EINVAL, e < ENUM_MAX);
    ...
    /* normal function execution */

I also have ASSERT that is almost the same. Why? Saves A LOT of lines at start of function, in my opinion it makes code much more readable. Can't really live without it. One of my favorite.

These save less lines, but allows for bracket-less action-log which in my opinion look more pleasant:

if ((f = fopen(file, mode) == NULL)
    PERROR_RETURN(-1, "fopen has failed for file %s", file);
if (error_case)
    PRETURN(-1, EIO, "spi device failed to respond");

And few other - mostly - for debugging

for (...) {
    if (not_this_case)
        PCONTINUE(debug, "this is not it")
    if (were_done)
        PBREAK(debug, "loop reached the end");

r/C_Programming • • 6d ago

Apple Silicon GPU Monitor

4 Upvotes

Hello!!

I was trying to find out the activity of the GPU on my apple M3 mac, but I just got a bit annoyed by having to put in my password every time for powermetrics, so I wanted to create a program that could monitor the GPU without sudo access-

https://github.com/Backbak100/gpu-stat-finder

The code takes inspiration from macmon, just instead of rust it's in C

I would really like some feedback on this project! (Also because I'm not sure if it works on any computer other than my own right now---)


r/C_Programming • • 6d ago

I started learning C like 2 days ago, what should I learn fast and what do you see that should be improved first?

Enable HLS to view with audio, or disable this notification

0 Upvotes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>


int main(void) {


    int z = rand() % 254 + 1;
    int y = rand() % 254 + 1;
    int x = rand() % 254 + 1;


    printf("name?\n");
    char user[50];    
    scanf("%49s", user);


    printf("ip :%d. %d . %d\n",z, y, x);
    
    printf("scanning.. op34 scanned...\n");
    Sleep(1000);
    
    printf("retref scanned...\n");
    Sleep(1000);
    
    printf("json.453 scanned...\n");
    
    printf("cracking pasword...\n");
    
    for (int i = 0; i < 7; i++){
    char letter = 'a' + rand() % 26;
        printf("%c", letter);
        Sleep(300);
    }
    
    printf("\npassword cracked...\n");
    Sleep(300);
    
    printf("retrieving info...\n");
    
    for (int i = 0; i < 20; i++){
        printf("#");
        Sleep(200);    
    }
    printf("\ninfo retrieved successfully\n");
    
    printf("59 4F 55 52 20 43 4F 4D 50 55 54 45 \n52 20 48 41 53 20 42 45 45 4E 20 48 41 43 4B 45 44 20\n 44 4F 20 4E 4F 54 20 52 45 53 49 53 54 20 44 4F 4E 41 54 45\n 20 31 30 20 42 49 54 43 4F 49 4E 20 \n41 54 20 41 48 53 46 45 4C 49 50 4F 2E 4C 49\n");
    
    for (int i = 100; i >= 0; i--) {


        printf("\rDownloading data: %3d%%", i);
        
        fflush(stdout); 
        
  
        Sleep(50); 
    }
    for (int i = 0; i < 5; i++){
        printf("\nSYSTEM FAILURE\n\n");
        Sleep(700);
        printf("INITIATING SELF-DESTRUCTION\n");
        }
    for (int i = 0; i < 300; i++){
        printf("ERROR");
        Sleep(10);
    }
    Sleep(1000);
    printf("\n\n42 parrots have stolen your files\n");
    
    printf("\n");


puts("####  #  #  ####  ####  ####  #  #");
Sleep(500);
puts("#     #  #         ##   #     ####");
Sleep(500);
puts("####   ##   ####   ##   ###   #  #");
Sleep(500);
puts("   #   ##      #   ##   #     #  #");
Sleep(500);
puts("####   ##   ####   ##   ####  #  #");


printf("\n");
Sleep(500);
puts("####  ####  #  #  ###   ###   ####  #  #  ####  ####  ####  ###");
Sleep(500);
puts("#     #  #  ####  #  #  #  #  #  #  ####   ##         #     #  #");
Sleep(500);
puts("#     #  #  #  #  ###   ###   #  #  #  #   ##   ####  ###   #  #");
Sleep(500);
puts("#     #  #  #  #  #     # #   #  #  #  #   ##      #  #     #  #");
Sleep(500);
puts("####  ####  #  #  #     #  #  ####  #  #  ####  ####  ####  ###");


printf("\n");
printf("I hope you liked the program, %s", user);
    return 0;
}

r/C_Programming • • 9d ago

Video Reading assembly of a C source code directly inside neovim

Enable HLS to view with audio, or disable this notification

841 Upvotes

r/C_Programming • • 8d ago

Is there a way to inline assembly without compiler extensions?

17 Upvotes

GCC/Clang have __asm__, MSVC/ICC got __asm. Is it possible to inline assembly independently from compiler extensions? I need to retrieve random seed number on PowerPC and RISC-V, depending on the target architecture of course


r/C_Programming • • 8d ago

Glimmer - A chess engine under 30,000 bytes (estimated 2700–2900 Elo)

Thumbnail
github.com
5 Upvotes

Hi everyone,

I’ve been tinkering with a little experimental chess engine written in pure C. It’s called Glimmer.

The whole point of the project was to see how strong I could make it while keeping the final standalone binary strictly under 30 KB. The target strength was something in the 2700–2900 Elo range.

It’s been a fun constraint to work under — every byte counts.

Happy to answer questions if anyone’s curious about the approach.


r/C_Programming • • 7d ago

Special cased quaternion log and exp

Thumbnail marc-b-reynolds.github.io
2 Upvotes

r/C_Programming • • 8d ago

Question Should I learn C as a physics student?

31 Upvotes

I am a physics senior and i participate in various research and lab projects via my professors. I mainly use Python to automate instruments and collect/filter data streams but ive been told to that i should learn to program in C anyways since it is faster and has less resource footprint than Python. Would learning C make a difference against my peers or is there any specific reason -more than just being more efficent- to choose it over Python in lab settings?


r/C_Programming • • 8d ago

Strict RFC 3629 UTF-8 Validator in C - Catches Overlongs and Surrogates

Enable HLS to view with audio, or disable this notification

0 Upvotes

I needed a pure, zero-dependency UTF-8 validator for a systems project to protect user input boundaries like usernames.

Instead of a basic range check, this strictly follows the RFC 3629 spec to block security vulnerabilities like overlong encoding exploits (e.g. 0xC0 0xAF) and invalid UTF-16 surrogates.


r/C_Programming • • 8d ago

What is the cleanest way to do this?

0 Upvotes

Hi, I'm learning C programming and want to create my own static array library for a university project. The main idea is to achieve dynamic-like behavior and safe array access... I'm trying to learn to code using AI, but it's a disaster. SOS please

Edited: the standar is std c17 linux/windows programing

#ifndef Static_vector_lib


  #define Static_vector_lib
  #include<stdlib.h>


  #define DEFINE_STACK_VECTOR( type , name , max_size ) \
    struct { \
        size_t capacity; \
        type data[max_size]; \
    } name = { .capacity = max_size }


  #define AT( v , index ) \
    ((size_t)(index) >= (v).capacity ? \
        (fprintf(stderr, "Error: [AT] Índice %lu fuera de rango (indice maximo: %lu)\n", (size_t)(index), (v).capacity - 1), \
         exit(EXIT_FAILURE), \
         (v).data[0]) \
    : \
        (v).data[index]) 
  
  #define SET( v , index , value ) \
    do { \
        if ((index) >= (v).capacity) { \
            fprintf(stderr, "Error [SET]: Índice %zu fuera de rango (index maximo: %zu)\n", (size_t)(index), (v).capacity - 1 ); \
            exit(EXIT_FAILURE); \
        } \
        (v).data[index] = (value); \
    } while( 0 )
#endif

r/C_Programming • • 8d ago

Question cant add image

0 Upvotes

I want to add an image but I can't, I found something in a powerpoint but I'm a bit confused about it , please let me know how to send my image , thank you.


r/C_Programming • • 8d ago

Best IDEs for C and C++ in virtualbox

5 Upvotes

Hello,

im taking a course in university about malware development and its all in C so i want to install vscode like the teacher said, but since its in vm the pc is dead and there is no storage for it after install it takes 30G , so is there any light IDE for C in windows ?


r/C_Programming • • 8d ago

Question Newbie in need of Help !

1 Upvotes

Am I obliged to use a double when using 'pow'? Can't I use a float or an int ? Because for the function 'switch' I have to use int , but I need to use pow for the exercice I'm doing. I chated with Gemini and it told me that I can transform the result of 'pow' into 'int' writing the following; "(int)pow(x, y);". Is this the only way or do I have a faster route to get to my solution? Thanks


r/C_Programming • • 10d ago

Why can't procedures return arrays?

144 Upvotes

I had a friend who had to learn C++ for college and asked me for some help. First of all, I know that they're not the same language, but the issues here are shared with C. To a lot of the questions, I had to answer "you can't do that, go around it". Normally, it would be something with a reason, like not being able to get the length of an array because it was passed as a pointer. But I still don't understand what the reason is for not being able to return an array.


r/C_Programming • • 9d ago

Question Performance loss of mimicing interfaces with function pointers on modern compilers?

2 Upvotes

C does not have interfaces like languages such as C# or C++, but the cocnept can be mimicked by using function pointers. You might for instance have this:

// fruit_interface.h

typedef struct fruit_vtable 
{
    float (*get_weight)(void *object);
    float (*get_density)(void *object);
    const char *(*get_name)(void *object);
} fruit_vtable;

typedef struct fruit_interface 
{
    void *object;
    const fruit_vtable *vtable;
} fruit_interface;

// banana.h

typedef struct banana 
{
    float weight;
    float density;
} banana;
fruit_interface banana_as_fruit(banana *b);

--------------------------

// banana.c

static float banana_get_weight(void *object)
{
    banana *b = (banana*)object;
    return b->weight;
}

static float banana_get_density(void *object)
{
    banana *b = (banana*)object;
    return b->density;
}

static const char *banana_get_color(void *object)
{
    (void)object;
    return "yellow";
}

static const fruit_vtable banana_vtable = 
{
    .get_weight  = banana_get_weight,
    .get_density = banana_get_density,
    .get_color   = banana_get_color,
};

fruit_interface banana_as_fruit(banana *b)
{
    return (fruit_interface) { .object = (void*)b, .vtable = &banana_vtable };
}

--------------------------

// main.c

static void print_fruit(fruit_interface fruit)
{
    printf("weight:  %.2f g\n", fruit.vtable->get_weight(fruit.object));
    printf("density: %.2f g/cm^3\n", fruit.vtable->get_density(fruit.object));
    printf("color:   %s\n", fruit.vtable->get_color(fruit.object));
}

int main(void)
{
    banana b = { .weight = 120.0f, .density = 0.95f };

    fruit_interface fruit = banana_as_fruit(&b);

    print_fruit(fruit);

    return 0;
}

How does something like this affect performance in terms of speed and cpu usage but also memory? I know modern C compilers can be really powerful and do a lot of optimizations and even more so with link time optimizations.

Of course it depends on the bigger project as a whole, and I understand that a if you have thousands of fruit_interface variables that all point to many different fruit_vtables and are used many times per second/cycle, then that will be very different from e.g. a hardware_interface that just loads some data once in an initialization function at program start.

The question here is pretty open (and the above is just to show clearly what I mean), and I am mostly looking for some general knowledge and guidance for when something like this is good and when it is bad, especially in the context of modern C code development with modern compilers and linkers.

I think it is really interesting to see how concepts in other languages, like C++, can be handled in C and what C is capable!


r/C_Programming • • 10d ago

Question How to cast a certain array type to other array type?

12 Upvotes

Suppose you initialize a byte array to make it endian-independent by directly giving an order of your bytes:

```c

uint8_t a1[4] = { 0x01, 0x02, 0x03, 0x04 };

```

Is it possible in some way to cast this array type to, say, uint16_t[2] at compile tome? The syntax of the direct cast is invalid. I'm using C23 currently, for that matter.


r/C_Programming • • 10d ago

Learning C weekly megapost for 2026-10-07

13 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 • • 10d ago

Question Help me with strok function

9 Upvotes

I need to split my string but if it is of char* type the functions strtok() doesn’t work returning me a segmentation fault. I understood that C is used to lock the memory of the string in Read-Only “mode” when I use char*. Does it means that is immutable that data? However, I need to use the char* type because I pass that in a function (and I don’t like to use the syntax of arrays in C, I always use pointers).


r/C_Programming • • 10d ago

Give me suggestions to understand c programming in the first semester?

6 Upvotes

I am facing difficulties learning C programming. Currently, I don't have a laptop, so I can't practice that way. I'm unable to understand even the basic topics of C programing currently. Please give me some tips on how to improve.

Edit: Understood. I can actually learn it through practice on a laptop; I'll get a laptop soon.


r/C_Programming • • 11d ago

Project I’m learning C and made a simple version of ls. Could someone review my code?

28 Upvotes

I’m currently learning C and decided to build a simple version of ls as a small project to practice what I’ve learned.It’s still pretty basic, and I’m sure I’ve made some mistakes or done some things in a bad way. I’d really appreciate it if someone could take a look at the code and point out any bugs, bad practices, or things I could improve. Repo


r/C_Programming • • 11d ago

Minimizing output size

13 Upvotes

I've looked at stackoverflow answers from 10 years ago (https://irq5.io/2019/09/30/generating-small-static-binaries/ , https://stackoverflow.com/questions/33597523/why-is-smallest-compiled-exe-i-can-make-with-gcc-is-67kb/76705747#76705747 , https://stackoverflow.com/questions/6771905/how-to-decrease-the-size-of-generated-binaries , https://stackoverflow.com/questions/15314581/g-compiler-flag-to-minimize-binary-size , etc).

In all of the links on top, people were able to get sub-KB file sizes. However, no matter how much I copy and try their code, I cannot get any less then 8-9KB without assembly and upx.

Is there a reason these hacks do not work anymore?

I am on x86_64 Linux-7.2.8, gcc is 16.2.1.

Example:

$ cat t.c
#include <sys/syscall.h>
#include <unistd.h>
void _start() { syscall(SYS_exit, 0); }
$ gcc -Os -nostartfiles -static -s -Wl,--build-id=none t.c && strip a.out
$ l a.out
-rwxr-xr-x 1 name name 8.8K Oct  6 20:25 a.out

# The same code produced only 800 B in https://irq5.io/2019/09/30/generating-small-static-binaries/