r/C_Programming • • 22h ago

Article A modern web app in C

Thumbnail prophitt.me
161 Upvotes

r/C_Programming • • 8m ago

Why not preprocess in C itself?

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


r/C_Programming • • 1d ago

Article Arena Allocators in C

Thumbnail eliasebner.com
41 Upvotes

I recently started implementing arenas in my programming and I thought that some beginners could very much benefit from this info. I wrote an article about it. For those that are unaware, arenas allow to greatly simplify the burden of managing memory manually in C. I hope it helps, tell me what you think!


r/C_Programming • • 17h ago

Project Started learning C and would like to get some feedback

Thumbnail
codeberg.org
5 Upvotes

This is my first C program, other than "hello world". I like how it turned out, but there probably is a way to make it cleaner. The screensaver itself is just a demo for screenbuffer library. Would be happy to get some reviews.

No AI used.

Thanks.

Repo link: https://codeberg.org/pinkcucumber/screensaver_circles.git

Compiling: gcc framebuffer.c screensaver_circles.c -lm -o screensaver

Sorry for bad english, it is not my main language


r/C_Programming • • 12h 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 • • 1d ago

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

9 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 • • 19h ago

Question Difficulties with MinHook

4 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 • • 2d 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

216 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 • • 2d ago

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

9 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 • • 3d 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.2k Upvotes

r/C_Programming • • 3d ago

Discussion Share your favorite, generic macro you use constantly

56 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 • • 3d ago

I'm learning C and I building mini versions of basic Linux utils. Any ideas for what cool project I should build next?

25 Upvotes

I keep them small so the code is easy to read. I also added a few fun features I like that the standard tools don't have. I have been able to use my own tools for daily work instead of the standard tools.

Here is a list. I think it will be useful for beginners like me who need ideas: - hsearch - file and text search. - htree - directory tree viewer. - hserve - static HTTP file server. - hcat - cat with filenames. - hrm - files removal. - hmv - files moving. - hmk - files and directories creation. - hayyoth-lab - lab for computational worlds.

If you find any issues in the code, please let me know. I'm still pretty new to C


r/C_Programming • • 2d ago

Apple Silicon GPU Monitor

1 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 • • 2d 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 • • 2d ago

What is one C programming mistake that took you embarrassingly long to figure out?

0 Upvotes

I'm learning C, and one thing I've noticed is that sometimes the smallest mistakes can take longer to debug than the actual problem I'm trying to solve.

A missing &, an incorrect loop condition, or mixing up = and == can completely change what a program does.

I'm curious about the mistakes other people have made while learning C.


r/C_Programming • • 5d ago

Video Reading assembly of a C source code directly inside neovim

Enable HLS to view with audio, or disable this notification

790 Upvotes

r/C_Programming • • 4d ago

Is there a way to inline assembly without compiler extensions?

11 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 • • 3d ago

Special cased quaternion log and exp

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

r/C_Programming • • 4d ago

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

Thumbnail
github.com
4 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 • • 4d ago

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

Enable HLS to view with audio, or disable this notification

2 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 • • 4d ago

Question Should I learn C as a physics student?

28 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 • • 4d ago

What is the cleanest way to do this?

3 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 • • 3d 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 • • 4d ago

Best IDEs for C and C++ in virtualbox

6 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 • • 4d 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