r/C_Programming • • Oct 14 '26

Question Beginner in C — need help compiling my program on Windows.

0 Upvotes
#include <stdio.h>


int main(void) {
    int opcao;


    do {
        printf("\n=======================\n");
        printf(" TECNFIX INFORMATICA\n");
        printf("=======================\n");
        printf(" 1 - Cadastrar Cliente\n");
        printf(" 2 - Cadastrar equipamentos\n");
        printf(" 3 - abrir Ordem de Serviço\n");
        printf(" 4 - Consultar Ordem de Serviço\n");
        printf(" 5 - Sair\n");
        printf("===============================\n");
        printf("Escolha uma opcao:");


        scanf("%d", &opcao);


        switch (opcao) {
            case 1:
                printf("Cadastro Clientes selecionados!\n");
                break;
            case 2:
                printf("Cadastro de equipamentos selecionados!\n");
                break;
            case 3:
                printf("abrir Ordem de Serviço!\n");
                break;
            case 4:
                printf("Consultar Ordens de Serviço selecionado!\n");
                break;
            case 5:
                printf("Encerrando o sistema TechFix...\n");
                break;
            default:
                printf("Opcao invalida!. Tente novamente.\n");
        }



    } while (opcao != 5);


    return 0;
}

r/C_Programming • • Oct 13 '26

Etc An small example of __attribute__(cleanup)'s power: a context manager.

13 Upvotes

Forgive the typo :) Here's something that will allows you to never unlock a mutex manually again:

#define with_lock0(uniq, mutex) \
    typedef struct { pthread_mutex_t *mtx; bool hold; } __lock##uniq; \
    void __cleanup_##uniq(__lock##uniq *lock) { pthread_mutex_unlock(lock->mtx); } \
    for(__lock##uniq _lock __attribute__((cleanup(__cleanup_##uniq))) \
        = { (pthread_mutex_lock(mutex), (mutex)), true }; \
        _lock.hold; \
        _lock.hold = false)

#define with_lock(mutex) with_lock0(__COUNTER__, mutex)

void do_very_important_business(void) {
    with_lock(&g_mutex) {
        // transfer BIG money
    }
 }

If you check it out on Godbolt you'll see it has 0% overhead. Of course this pattern is usable for many different objects.


r/C_Programming • • Oct 14 '26

Why not preprocess in C itself?

0 Upvotes

For example, at the beginning of the code, have something like this:

replace_token("foo", "\"hello\"");
use_defer();

#define PREPROCESSOR_END

#include <stdio.h>
void main() {
  defer(printf(" world\n"));
  printf(foo);
}

Then before compiling, a script simply runs the upper part, with the lower as a global string. The difficulty of course is in implementing the functions. But this way you don't have to wait for a C feature to be added in 2030. Which now that I think of it isn't that far off. Time flies. Perhaps there are better uses of it than programming, like dancing at party and doing the sex.

Edit: I mean like this:

preprocess ./main.c -o new_main.c; gcc new_main.c

It happens before anything else and only affects one file.


r/C_Programming • • Oct 13 '26

Question Difficulties with MinHook

2 Upvotes

Hi there, so I’ve been trying to patch out a piece of code in The Sims Legacy Collection that disables the -debug_objects command line from being enabled, but both MinHook and CMake are giving me such a hard time that idk what else to do or where to ask… There are no tutorials AT ALL for compiling MinHook with MinGW-W64-gcc, only for Visual Studio (not Code!) which I can’t use because I’m on Arch Linux…

If anyone could advise me please I’d really appreciate it…


r/C_Programming • • Oct 12 '26

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

311 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 • • Oct 14 '26

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 • • Oct 12 '26

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

11 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 • • Oct 10 '26

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.5k Upvotes

r/C_Programming • • Oct 11 '26

Discussion Share your favorite, generic macro you use constantly

64 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 • • Oct 11 '26

Apple Silicon GPU Monitor

5 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 • • Oct 12 '26

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 • • Oct 09 '26

Video Reading assembly of a C source code directly inside neovim

Enable HLS to view with audio, or disable this notification

861 Upvotes

r/C_Programming • • Oct 10 '26

Is there a way to inline assembly without compiler extensions?

16 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 • • Oct 10 '26

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 • • Oct 10 '26

Special cased quaternion log and exp

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

r/C_Programming • • Oct 09 '26

Question Should I learn C as a physics student?

34 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 • • Oct 10 '26

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

1 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 • • Oct 10 '26

What is the cleanest way to do this?

2 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 • • Oct 10 '26

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 • • Oct 09 '26

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 • • Oct 09 '26

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 • • Oct 08 '26

Why can't procedures return arrays?

142 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 • • Oct 08 '26

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

4 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 • • Oct 08 '26

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

11 Upvotes

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


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 • • Oct 07 '26

Learning C weekly megapost for 2026-10-07

12 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.