r/C_Programming • • Feb 23 '24

Latest working draft N3220

134 Upvotes

https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf

Update y'all's bookmarks if you're still referring to N3096!

C23 is done, and there are no more public drafts: it will only be available for purchase. However, although this is teeeeechnically therefore a draft of whatever the next Standard C2Y ends up being, this "draft" contains no changes from C23 except to remove the 2023 branding and add a bullet at the beginning about all the C2Y content that ... doesn't exist yet.

Since over 500 edits (some small, many large, some quite sweeping) were applied to C23 after the final draft N3096 was released, this is in practice as close as you will get to a free edition of C23.

So this one is the number for the community to remember, and the de-facto successor to old beloved N1570.

Happy coding! 💜


r/C_Programming • • 1d ago

Learning C weekly megapost for 2026-12-02

10 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 • • 5h ago

A Better UTF-8 Automaton

Thumbnail orlp.net
12 Upvotes

r/C_Programming • • 47m ago

Coding a satisfying animation in C / Raylib

Thumbnail
youtu.be
0 Upvotes

Tons of YouTube channels are making really nice physics animations. Most of them look quite similar, and I suppose everyone's vibecoding them. Anyways, vibecoding or not, I love these animations, and I want to learn how to code them myself.

The problem is that most of these channels don't really share the implementation details.

Well... in this video, I'm building one from scratch. So, if you want to learn how to program these kinds of animations, I'm providing the clean source code and the full coding session so you can follow along.

AI Disclaimer:
I didn't use AI.

Source code:
https://github.com/FractalCodeRicardo/dopamine-programming/tree/main/squares-balls

#include <raylib.h>
#include <raymath.h>
#include <stdbool.h>
#include "time.h"

#define screenSize 800.0
#define gridSize  25.0

typedef struct{ 
  Vector2 pos;
  Vector2 dir;
  Color color;
} Ball;

typedef struct{ 
  Vector2 pos;
  Color color;
  bool empty;
  int life;
} Square;

typedef struct{ 
  Ball items[2500];
  int size;
} Balls;

typedef struct{ 
  Square items[2500];
  int size;
} Squares;

Squares squares;
Balls balls;

float squareSize;
float ballSize;

Sound sound;

Color RandomColor() {
  Color colors[] = {
    GREEN, YELLOW, RED, BLUE, PURPLE,
    ORANGE, BROWN, SKYBLUE, DARKPURPLE, MAGENTA
  };

  int index = GetRandomValue(0, 9);
  return colors[index];
}

Vector2 RandomDir() {
  float sign[] = {1 , -1};

  float x = GetRandomValue(5, 10) / 10.0;
  float y = GetRandomValue(5, 10) / 10.0;
  
  x = x * sign[GetRandomValue(0, 1)];
  y = y * sign[GetRandomValue(0, 1)];

  return (Vector2) {
    x, y
  };
}

void InitSquares() {
  squareSize = screenSize / gridSize;
  
  int center = gridSize / 2;
  for(int y = 0; y < gridSize; y++) {
    for(int x = 0; x < gridSize; x++) {

      bool empty = false;
      if (x >= center - 2 && x <= center + 2)
        if (y >= center - 2 && y <= center + 2)
          empty = true;


      int i = y * gridSize + x;

      squares.items[i] = (Square) {
        (Vector2) { 
          x * squareSize,
          y * squareSize
        } ,
        RandomColor(),
        empty,
        5
      };

      squares.size++;
    }
  }
}

void InitBalls() {
  ballSize = (screenSize / gridSize) / 2;
  
  float center = screenSize / 2;
  for(int i = 0; i < 4; i++) {
    balls.items[i] = (Ball) {
      (Vector2) { center, center} ,
      RandomDir(),
      RandomColor()
    };

    balls.size++;
  }

}

void Init() {
  InitSquares();
  InitBalls();
}

void DrawSquares() {
  for (int i = 0; i <squares.size; i++) {
    Square s = squares.items[i];

    if (s.empty)
      continue;
    
    DrawRectangle(
        s.pos.x + 1,
        s.pos.y + 1,
        squareSize - 1, 
        squareSize - 1, 
        s.color);
  }
}

void DrawBalls() {
  for (int i = 0; i <balls.size; i++) {
    Ball b = balls.items[i];
    
    DrawCircle(
        b.pos.x ,
        b.pos.y,
        ballSize / 2,
        b.color
        );
  }
}

void Draw() {
  DrawSquares();
  DrawBalls();
}

void ChangeSquareColor(Square *s) {
  s -> color.a = s -> color.a - 10;
}

void AddBall(Vector2 pos) {
  if (balls.size >= 1000)
    return;

  balls.items[balls.size] = (Ball) {
    pos ,
    RandomDir(),
    RandomColor()
  };

  balls.size ++;
}

void HandleCollision(Ball *b) {

  Rectangle ballRect = (Rectangle) {
    b -> pos.x - ballSize/2,
    b -> pos.y - ballSize/2,
    ballSize,
    ballSize,
  };

  for(int i = 0; i < squares.size; i++) {
    Square *s = &squares.items[i];

    if (s -> empty)
      continue;

    Rectangle squareRect = (Rectangle) {
      s -> pos.x,
      s -> pos.y,
      squareSize,
      squareSize,
    };

    Rectangle collision = GetCollisionRec(ballRect, squareRect);

    if (collision.width <= 0 ||
        collision.height <= 0)
      continue;

    if (collision.width < collision.height)
      b -> dir.x *= -1;
    else
      b -> dir.y *= -1;

    s -> life--;
    ChangeSquareColor(s);

    if (s -> life <= 0) {
      s -> empty = true;
      AddBall(b -> pos);
    }

    PlaySound(sound);

    return;

  }
}

void MoveBalls() {
  for(int i = 0; i < balls.size; i++) {
    Ball *b = &balls.items[i];
    b -> pos = Vector2Add(b -> pos, b -> dir);
    HandleCollision(b);
  }
}

void Update() {
  MoveBalls();
}

int main() {
  SetRandomSeed(time(NULL));
  Init();
  SetTargetFPS(200);
  InitAudioDevice();
  sound = LoadSound("jump.wav");
  SetSoundVolume(sound, 0.1f);
  InitWindow(screenSize, screenSize, "Squares/Balls");

  while(!WindowShouldClose()) {
    BeginDrawing();
    ClearBackground(BLACK);
    Draw();
    Update();
    EndDrawing();
  }
  CloseWindow();
}

r/C_Programming • • 11h ago

Review Help with seed generation for RNG.

6 Upvotes
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;

typedef float f32;
typedef double f64;

i8 RANDOM_SEED(){
    static i8 seed = 0;
    static i8 init = 0;

    if (init) return seed;

    FILE *pF = fopen("SEED_FILE", "rb");

    if (pF) {
        fread(&seed, sizeof(i8), 1, pF);   
    }
    else {
        i8 created = 0;

        srand((u32)time(NULL));
        seed = (i8)(rand() % 246 - 128);

        do {  
            pF = fopen("SEED_FILE", "wb");
            if(pF){
                fwrite(&seed, sizeof(i8), 1, pF);
                created = 1;
            }
        } while(created != 1);
    }

    fclose(pF);
    pF = NULL;
    init = 1;
    return seed;
}

I'm trying to make a seed generator. How it works: you call the function and it creates a seed file with a raw binary value inside it that cannot be read by a human. The program reads it and produces a seed that will always be the same for one computer but will vary from computer to computer. I will use it to make a random number generator whose output is constant on the same machine but differs across machines. Can you tell me if this is efficient, or am I overdoing, underdoing, or overcomplicating things? And also I want to make it memory efficient.
I am making this to clarify my concept on file reading - writing and RNG.


r/C_Programming • • 4h ago

Guia Técnico C Freestanding na prática: primitivas de memória, volatile em MMIO e Linker Script (com bancada de teste no OnlineGDB)

0 Upvotes

Quando alguém começa a estudar kernels, firmwares ou bare metal, geralmente trava em duas frentes ao mesmo tempo: entender a lógica de baixo nível em C e configurar cross-compiler, linker scripts e emuladores.

Uma forma produtiva de quebrar essa barreira é usar um compilador online (como o OnlineGDB) apenas como bancada de teste lógico (sabendo que ele roda em ambiente hosted com stdio.h), antes de levar o código para compilação freestanding real.

Aqui vai um resumo técnico direto dos 4 pilares dessa transição:

1. O que muda na norma ISO/IEC 9899 (Hosted vs. Freestanding)

No ambiente freestanding (__STDC_HOSTED__ == 0), você não tem libc nem sistema operacional. O padrão garante apenas cabeçalhos de definição e tipos (<stddef.h>, <stdint.h>, <stdbool.h>, <stdarg.h>, <limits.h>, <float.h>, <iso646.h>, <stdalign.h>, <stdnoreturn.h>).

Funções como printf, malloc, strlen, memset e memcpy não existem até você implementá-las.

2. Primitivas de memória sem libc (usando unsigned char *)

Ao reescrever funções como memset, memcpy e memcmp, o cast para unsigned char * evita problemas de extensão de sinal e respeita a regra de strict aliasing do C para acesso byte a byte:

C

#include <stddef.h>

size_t meu_strlen(const char *str) {
    size_t len = 0;
    while (str[len] != '\0') len++;
    return len;
}

void *meu_memset(void *destino, int valor, size_t qtd) {
    unsigned char *dst = (unsigned char *)destino;
    unsigned char byte_val = (unsigned char)valor;
    for (size_t i = 0; i < qtd; i++) dst[i] = byte_val;
    return destino;
}

void *meu_memcpy(void *destino, const void *origem, size_t qtd) {
    unsigned char *dst = (unsigned char *)destino;
    const unsigned char *src = (const unsigned char *)origem;
    for (size_t i = 0; i < qtd; i++) dst[i] = src[i];
    return destino;
}

Detalhe importante de compilação: mesmo com -ffreestanding, o GCC pode reconhecer loops de cópia/preenchimento e gerar chamadas implícitas para memcpy/memset. Por isso, na compilação real usamos:

gcc -ffreestanding -fno-builtin -nostdlib -nostdinc -Wall -Wextra -c kernel.c -o kernel.o

3. Acesso a registradores MMIO e volatile

Em hardware real (Memory-Mapped I/O), periféricos são endereços físicos de memória. Sem volatile, o compilador pode eliminar leituras repetidas ou descartar escritas que considera redundantes:

C

#include <stdint.h>

/* Exemplo em hardware real:
 * #define UART_DR (*(volatile uint32_t *)0x40000000U)
 */

static inline void mmio_write8(volatile uint8_t *reg, uint8_t val) {
    *reg = val;
}

static inline uint8_t mmio_read8(const volatile uint8_t *reg) {
    return *reg;
}

(Nota: volatile impede otimizações indevidas do compilador, mas não substitui barreiras de memória de CPU como mfence ou dmb quando há DMA ou múltiplos cores).

4. Layout de memória com Linker Script

Sem um carregador de SO, o linker script define o ponto de entrada (_start) e o endereço físico/virtual de cada seção:

código

ENTRY(_start)

SECTIONS
{
    . = 0x00100000;

    .text ALIGN(4096)   : { *(.text*) }
    .rodata ALIGN(4096) : { *(.rodata*) }
    .data ALIGN(4096)   : { *(.data*) }
    .bss ALIGN(4096)    : {
        __bss_start = .;
        *(COMMON)
        *(.bss*)
        __bss_end = .;
    }
}

Antes de chamar a função principal em C, a rotina _start precisa configurar a pilha (stack pointer) e zerar o intervalo entre __bss_start e __bss_end.

Para quem trabalha com sistemas embarcados, firmware ou OS dev: quais outras armadilhas de compilador ou ligação vocês costumam ver quem está migrando de C hosted para freestanding cair logo no início?

Referências

ISO/IEC 9899 (C11 Draft N1570) — Programming languages — C, Seção 5.1.2 (Execution environments). Disponível em: https://open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

OSDev Wiki — Freestanding. Disponível em: https://wiki.osdev.org/Freestanding

OSDev Wiki — Bare Bones. Disponível em: https://wiki.osdev.org/Bare_Bones

OnlineGDB — Online C Compiler. Disponível em: https://www.onlinegdb.com/online_c_compiler


r/C_Programming • • 20h ago

How to read special characters from a text file?

12 Upvotes

Hello, I'm doing a little project to improve myself in C. The issue I hit is that non-ASCII characters like 'é' take multiple bytes in UTF-8, so my loop treats them like multiple characters instead of a single one. I don't know how to solve it, can anyone help me with a pretty simple solution because everything that I read online is too complex!
Here is the code if you want to help me:

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>


int count_words(FILE *file);
int total_char = 0;


int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Format: ./stats file.txt\n");
        return 1;
    }
    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        printf("Couldn't open the file %s\n", argv[1]);
        return 1;
    }
    int words = count_words(file);
    printf("Words: %i\n", words);
    fclose(file);
    return 0;
}


int count_words(FILE *file)
{
    int n = 0;
    char character;
    bool word = false;
    while (fread(&character, 1, 1, file))
    {
        if (isspace(character) == 0 && ispunct(character) == 0)
        {
            if (word == false)
                n++;
            total_char++;
            word = true;
        }
        else
        {
            word = false;
        }
    }
    return n;
}

Thanks for any help!


r/C_Programming • • 13h ago

Project I wrote an AI agent in C: one static binary, no runtime, no Node or Python

Thumbnail
github.com
0 Upvotes

What it actually does

Every message is a task. Not a chat bubble you wait on. Tasks have visible states, run in the background, and you keep typing while they work.

Compose tasks like shell pipelines. | passes one task's output to the next, & runs in the background, ; sequences them, @path#40-80 attaches a line range to the prompt:

"Summarize @design.md in three bullets." | "Turn that into a two-sentence announcement."

Fork instead of re-explaining. /task fork branches a task with its context intact.

Groups and sessions. Groups share conversation history; a session binds groups to a working directory, so reopening from the same directory picks up where you left off. /session save then /task resume <id> continues work that was interrupted mid-flight.

Memory and skills. Session memory is searchable across groups. /prompt and /skill run reusable templates; it already reads .claude, .agents, .opencode and .pi resource directories, so existing agent configs mostly work.

MCP servers. Streamable HTTP and stdio, configured in ~/.edgeclaw/mcp.json, tools show up as mcp__<server>__<tool>.

Scheduled jobs. Run a prompt on a cron schedule without keeping a terminal open.

Why C, and what it cost

The goal was curl | sh actually meaning one file. That forces you to build things yourself instead of pulling a package:

  • the input box is a real language (|, &, ;, @path#40-80, quoted text), so it's a flex lexer and a bison grammar — 354 + 400 lines of .l/.y;
  • TLS and HTTP are mbedtls plus a hand-rolled client, including the SSE stream the MCP client needs;
  • state is SQLite, forward-only migrations, no rewriting a JSON blob every turn.

Security matters more than usual here, because the model can run shell commands. On Linux the sandbox is Landlock for path access plus a seccomp-BPF filter — Landlock doesn't mediate metadata mutators like FS_IOC_SETFLAGS, so those need seccomp. /sandbox list shows the resolved writable / read-only / denied sets. On macOS it's Seatbelt.

Numbers, measured on the published binary

  • 73.2 MiB as published (71.6 stripped), of which 59.2 MiB is tree-sitter parse tables for syntax highlighting. They're file-backed and demand-paged, so first-screen RSS is 4.7 MB, not 73.
  • --version starts in 0.4 ms; TUI first paint in a PTY in 3-4 ms.
  • RSS after a long session: ~92 MB (measured with 1793 tasks / 80k messages in the store). Most of that is the TUI's chat model plus glibc arenas, not the grammar tables — only ~9 MB is file-backed.
  • 187 cc_test targets, 173/173 green; 69.49% line coverage per Codecov.

r/C_Programming • • 1d ago

Discussion Thoughts on safe-c

8 Upvotes

Has anyone here come across the safe-c project? If so, what do you think of it? If not, do you think a project like this could actually make C (and C++) safer and more attractive in certain fields? Curious to hear what people think.


r/C_Programming • • 2d ago

Flat structures VS nested structures?

29 Upvotes

Hello!
I have this deep conflict that has been with me for months now. How is it better, flat structures or nested structures? Or what do you prefer?

Flat example :
struct entity = {
int x = 20;
int y = 40;
string texture = "mario.png";
int current_health = 100;
int current_armor = 100;
}

Nested example :
struct position = {
int x = 20;
int y = 40;
}
struct stats = {
int current_health = 100;
int current_armor = 100;
}

struct renderable = {
string texture = "mario.png"
}
struct entity = {
position position;
stats stats;
texture texture;
}

I have tried to use nested structures as often as possible because that's the norm but they are becoming a pain in my experience. Mostly, it comes down to boilerplate, the risk of getting paths wrong when there's too much nesting and theoretical purity where I find that a property would've worked better in another component.

But with flat structures? I get much better results, more directness, easier debugging and less cognitive load as a property is defined in only one way, even if the names get longer or repetitive. Also, that's how computers like to think and as a CS engineer, I learned how computers think before learning how humans program so I lean towards more old school polling / procedural algorithms.

If I were to make an analogy of how that makes me feel, it would be like owning a big tools box. When I open the box, I can instantly see and pick or place the drill, the screwdriver, the screws and whatever else is there. But with nesting... if feels like after opening the tools box, that the drill has it's own mini-box, that the screws are in another box and so on. I prefer seeing the whole picture at once instead of always having to deal with involvement at micro-scales of a big thing.

Also, I noticed that older games like Doom are closer to flat structs. The thing is, my game isn't very complex in terms of gameplay and it features multiplayer matchmaking. And it's on the server side where I noticed that a flat structure would be much easier for debugging, serialisation and overall faster development speeds.


r/C_Programming • • 2d ago Bravo

Article Zero-initialisation shenanigans

Thumbnail napcakes.nekoweb.org
47 Upvotes

r/C_Programming • • 2d ago

Question Need help avoiding circular dependency

8 Upvotes

[Solved but I'll gladly accept new solutions]

I am making a small clone of asteroids on C and plan to use the observer pattern described in Game Programming Patterns by Bob Nystrom. (Adapted to C) To do so, I currently have 2 files, a stats system (stats.h/c) and the actual observer pattern code (event.h/c). (Relevant Source code below)

My problem is that stats.h/c requires access to structs and enums defined in event.h, but event.h has a struct that contains a union with a struct defined in stats.h, and I don't know how to solve the circular dependency.

stats.h and stats.c (implementation of statsOnNotify lies in C file)

struct Stats { ... };

// statsOnNotify requires struct Observer and enum EventType, defined in event.h 
void statsOnNotify(struct Observer \*observer, enum EventType event, void \*data) {
  switch (event) { 
    case ...: { 
      //Access Observer union to access the struct Stats data 
    } 
  break; 
  }
}

event.h

enum EventType { ... };

struct Observer;

// Requires struct Observer and enum EventType. 
typedef void (\*NotificationHandler)(struct Observer \*observer, enum EventType event, void \*data);

enum ObserverType { ... };

// struct Observer requires struct Stats, defined in stats.h 
struct Observer { 
  enum ObserverType type; 
  union { 
    struct Stats stats; 
  } data; 
  NotificationHandler onNotify; 
};

r/C_Programming • • 1d ago

GitHub - safe-c-project/safe-c: C and C++ with memory safety guarantees as strong as Rust

Thumbnail
github.com
0 Upvotes

Hi, I'm not the author of this repo but I find it interesting to say the least, I've already followed Fil-C progress but I will try safe-c on my project for sure and give some feedback.


r/C_Programming • • 1d ago

Streamside: a native C viewer for Twitch, Kick, and YouTube Live with embedded chat

Thumbnail
streamside.lessif.org
2 Upvotes

Sharing a C project I've been working on: a single-window viewer for Twitch, Kick, and YouTube Live streams + chat without Electron, Python, or yt-dlp.

It embeds libmpv into an SDL2/OpenGL window alongside a custom chat pane (Twitch IRC over WebSocket, Kick Pusher WebSocket, YouTube InnerTube polling, plus inline emote/emoji rendering) and resolves HLS directly with libcurl. Builds statically on Linux and cross-compiles to a standalone Windows exe with mingw-w64.

Demo + MIT source tarball here: https://streamside.lessif.org/

Feedback on the code or build setup is welcome.


r/C_Programming • • 2d ago

Project I Made a 3D .OBJ Viewer with Software Rendering and a Custom Parser

Thumbnail
github.com
3 Upvotes

To get better at computer graphics, I created a .OBJ file viewer that uses software rasterization and only depends on SDL3 and its child libraries. It supports materials, texture mapping, Phong shading, Phong illumination, and near clipping.

This is my first big C project, so any feedback / constructive criticism is appreciated (especially on the code).

No AI was used.


r/C_Programming • • 2d ago

Project I wanted a modern alternative to C, so I started building Elash

0 Upvotes

So, I like C. I like how simple it is and I just like using it. I'm tired of overcomplicated languages. But of course C is not a perfect language. There are so many features I'd really like to have. So many things that could be improved or redesigned in a better way. So many bad decisions and suboptimal tradeoffs.

If you don't care, you can just scroll to "The Elash language" section. I know I should've show some code example here to actually get you interested but I currently don't have much to show. But... here's a "game" made with SDL3 in Elash!

My problems with C

I'm very happy with C's philosophy, but there are some things I've always wished it did differently.

  • Native tagged unions: In C, you usually build them as a struct with an enum tag plus a union (or use tricks like a common tag header in every variant). All of these require a lot of boilerplate, and there's no pattern matching. I don't think full pattern matching is strictly necessary, but I'd LOVE something like if (SomeVariant v = my_union) use(v);. In C it's more like if (my_union.kind == MYUNION_SOME_VARIANT) use(my_union.as.some_variant);, and you repeat the field name every time. However you define it, it's never as convenient as a built-in tagged union, and the compiler can't enforce safety or stop you from accessing random fields before checking which one is actually active.
  • Optional types: For an optional int in C, you use a sentinel value such as 0, -1, or maybe even INT_MAX/INT_MIN depending on which values you don't need. If you really need the whole range, you can wrap it in a struct with a bool has_value; field, which is really inconvenient, at least for me. On the other hand, we have pointers, and they have the standard NULL constant, but the problem is every pointer is "optional": there's no way to encode a pointer that can't be NULL in C's type system, so you rely on comments and docs, and the compiler doesn't read those or enforce them. There are compiler-specific "solutions" like __attribute__((nonnull)), but that's just not the same thing.
  • More advanced preprocessor: Many people will disagree, but I think the concept of a preprocessor separate from the core compiler is a great thing. But CPP is very limited and requires hacks if you want to use it for something more complex. It doesn't support recursion and iteration in a normal way and it cannot evaluate expressions (I mean, it can, but only in #if directives).
  • Slice types: To declare a function that takes a slice you usually write (int* xs, size_t count), and to store one you need two struct fields like things and things_count. That's inconvenient. It's much better to store a slice in one variable without defining your own struct every time you need a slice of a type that doesn't already have one. And int[] xs looks better than IntSlice xs (:
  • Declaration syntax: No need to explain. It's just terrible. But people don't get why. It's not because the type comes before the variable name. You can design readable, consistent type-first syntax. What separates good and bad declaration syntax is whether it reads naturally left to right or right to left without parentheses. Just reversing C's syntax doesn't make it readable. (*signal(int, (*)(int): void)): void isn't any better than void (*signal(int, void (*)(int)))(int);. But void(int)* signal(int, void(int)*); is, because it reads cleanly left to right. Typedefs only partly solve this, and there are still footguns like int* x, y;.
  • Weak type aliases: Typedefs in C are only aliases. You can use the typedef and the original type interchangeably. You can wrap the type in a struct, but then you lose access to operators etc. It would be nice to have some way to define "strong type aliases", like in Go.
  • No defer: Pretty obvious, defer statements are really useful and C just doesn't support them. If you follow recent C standards you may know that this feature is slated for C29, but that standard will be released around 2029 and it'll take a few more years before it's production ready.

There are so many other examples, that I will not explain all of them, but a few more examples are: Bad standard library, No built-in collections, char vs unsigned char vs signed char, Built-in string views, Arrays as first class values, Loops over collections, Embedding files at compile time (C23 added #embed but most compilers don't support it yet), Anonymous functions, Implicit narrowing conversions, ...

The Elash language

I know of C3, Zig and other languages that tried to "replace C" but none of them is quite what I wanted, and also I want[ed] to learn langdev and compiler architecture, so I decided to create my own programming language, called Elash (the name doesn't mean anything, it just sounds cool).

It obviously won't "replace C", and that was never the goal. As I already said, I wanted to learn compilers architecture and experiment with designing my own language just how I want to.

It's meant to be a really simple, relatively low-level language that is [semi-]familiar to C developers, convenient to use, and fixes the issues listed above.

I started the project about 9 months ago, I took a couple of breaks but I was working on it regularly for a very long time, initially with a friend of mine but later I became the only maintainer. The project isn't finished. In fact, it's still in the early developement stage, though it's already (kind of) usable for simple tasks. Writing a programming language takes time and you can’t just finish it in a week like many vibecoded languages posted here and on other subreddits.

The compiler is written in C using the LLVM C API (it's built as a multi backend compiler from the start though currently LLVM is the only backend)

I'm looking for people interested in the project; if you want to contribute to the language, share your ideas or just see how development is going, you might want to join the Discord server I've just created. And here is the GitHub repository.


r/C_Programming • • 2d ago

I built CLAP to make it easier to compile a C file on Windows

0 Upvotes

I maintain CLAP, an open-source command-line frontend for C and C++. The use case is a small C program on a fresh Windows machine. With Python installed, you can install CLAP with `python -m pip install clap-compiler` and build a local `main.c` with `clap build main.c -o hello`. If needed, CLAP downloads a pinned Zig/Clang toolchain on the first build. It also supports multi-file projects and CMake.

I’d like feedback from people who teach or learn C on Windows. What would you expect a tool like this to show when the first build fails, and what would make the compiler setup easier to understand?

Source and examples (MIT): https://github.com/BRATAN-CORP/clap

c now is easy, as never before...


r/C_Programming • • 3d ago

Project HimitsuObfuscator: Whitelist-driven C/C++ obfuscator with LLVM 17

Thumbnail
github.com
3 Upvotes

Obfuscation can cause build errors or unexpected runtime behavior when transformations are applied too broadly.

I built each obfuscation pass around a whitelist, so only instructions considered safe for each transformation are selected.

It supports Linux on x86_64 and aarch64, with control flow flattening, bogus control flow, instruction substitution, string encryption, and basic block splitting.


r/C_Programming • • 3d ago

Project Wrote a multi-core-native, SIMD lossless compression codec, originally for my engine, but just released to github with permissive license!

Thumbnail
github.com
0 Upvotes

Hey everyone,

I originally built this compression algorithm for my own game engine because I wanted an open-source middle ground between LZ4 and Zstd for game dev workloads (paks, streaming assets, snapshots, small netcode packets). Full disclosure: I have background in network and low-level optimization, and I used AI to help me bridge the domain gap in compression itself while steering the architecture, profiling, and verifying everything on real hardware.

It turned out useful enough that I split it into a standalone zero-dependency library + CLI in both C11 and native Odin (100% wire-compatible, Apache-2.0, Linux/macOS/Windows):

https://github.com/JoseIgnacioAragon/axz

Quick numbers on the standard 202 MiB Silesia corpus (Intel Core 7 240H, AVX2, in-memory):

  • AXZ -1: 2.21x | 3.36 GiB/s 1T / 17.0 GiB/s 16T decode
  • AXZ -5: 2.90x | 3.24 GiB/s 1T / 17.0 GiB/s 16T decode (matches Zstd -1 ratio while decoding ~2x faster 1T and ~11x faster 16T, since standard Zstd frames don't parallelize decode)
  • On a 32T Ryzen 9 7950X (AVX-512VBMI2) it scales up to 58 GiB/s multi-core decode.

It's multi-core native in the wire format, skips bit-level Huffman/ANS in favor of SIMD planar tables, and includes 11 per-chunk pre-filters (RGBA8, Float4_Xor, Delta, SoA, etc.) plus 8-byte micro-packets + 8 KiB dictionaries for small RPC/netcode payloads. ARM64 NEON isn't in yet (runs scalar fallback for now), and -5 is intentionally slow to encode for offline asset cooking.


r/C_Programming • • 3d ago

Video Coding a fractal Kaleidoscope using C & GLSL

Thumbnail
youtu.be
12 Upvotes

In this video I create a classic kaleidoscope fractal animation using Raylib, C and GLSL.

I follow these steps:

  1. First, I split the screen into slices (like a pizza) using polar coordinates.
  2. Then, I create a well-known pattern in fractal shaders: sin(x) * sin(y), inside each slice.
  3. Next, I add a color palette to generate some nice colors.
  4. Finally, I use time as a parameter in different parts of the shader to animate both the pattern and the colors.

Source code:
https://github.com/FractalCodeRicardo/zen-programming/tree/main/kaleidoscope

C part

#include <raylib.h>

#define size 800

float time = 0.0;
int main() {

  InitWindow(size, size, "Kaleidoscope");
  
  Shader shader = LoadShader(0, "kaleidoscope.glsl");
  int timeLoc = GetShaderLocation(shader, "time");
  
  while(!WindowShouldClose()) {
    
    time = GetTime();
    SetShaderValue(shader, timeLoc, &time, SHADER_UNIFORM_FLOAT);

    BeginDrawing();
      ClearBackground(BLACK);
      BeginShaderMode(shader);
        DrawRectangle(0, 0, size, size, BLACK);
      EndShaderMode();
    EndDrawing();
  }

  CloseWindow();
}

GLSL part

void main() {
  float pi = 3.1416;

  vec2 uv = gl_FragCoord.xy / 800;
  uv = uv - 0.5;

  float angle = atan(uv.y, uv.x) * time * 0.3;
  float radius = length(uv);

  float slices = 3;
  float size = pi * 2 / 3;
  float internal_angle = mod(angle, size);
  internal_angle = abs(internal_angle - size /2.0);
  
  vec2 internal_point= radius *
    vec2(
        cos(internal_angle) * radius,
        sin(internal_angle) * radius
        );

  float pattern = 
    sin(internal_point.x * time *10 * 0.5) * 
    sin(internal_point.y * time *10 * 0.5);

  vec3 c = palette(pattern + time * 0.5);

  color = vec4(c, 1);
}

AI Disclaimer:

I used AI to understand the fractal then I coded my own version


r/C_Programming • • 3d ago

C beginner

10 Upvotes

hello, i love the c programming language, and i want someone that is also a beginner like me to help each other get better, right now working on a project "text editor"


r/C_Programming • • 4d ago

Question Design choice with enums and strings

8 Upvotes

I'm working on a C minecraft clone, and I've been refactoring a bunch of my block code. Previously a "block" was just an enum, I essentially "hardcoded" the list of blocks in the game itself. Part of the refactor is using a JSON file for defining blocks and their metadata. However, because of this, I've now reached a weird place. The JSON defines the ID as a string. The enum that was BLOCK_GRASS is now a string in the JSON as "BLOCK_GRASS".

The design question I have is should I be referencing a string in my code, and doing comparisons with strings? Or do I need to have some sort of intermediate mapping of string IDs -> enum IDs. The latter seems kind of wasteful since it just means all the benefits of the JSON config file went away.

Not sure what the general consensus is. The strings are going to be in the data section anyways so I don't think I'm being wasteful with allocations here.


r/C_Programming • • 4d ago

Question What is the most high-level C feature in your opinion?

156 Upvotes

I'm asking this purely out of curiosity.

I've been programming in C for a couple of years now, and I recently dived into some x86-64 assembly. I was surprised by how similar some asm concepts were to using C. Known by some as a "portable assembler", C is probably one of if not the most low-level language one can use that is not raw assembly language.

But what is the most high-level feature C supports? Standard library features do not count.

Honestly? I think it has gotta be structs / unions, right? Sizeof is really powerful and having automatic variable offsets that adapt as you upgrade your code is something I totally missed quite a lot when using MASM.


r/C_Programming • • 3d ago

looking for modern c text editors

0 Upvotes

ive been writing c for 6 months now and i keep on hopping onto different ides and text editors because frankly i dont really like them, i have been using vim , neovim , codium and vscode, code::blocks, codelite but i dont really like them especially the last 2. they have a retro look to them and im not a fan. vscode is too heavy for me considering i use a 4gb ram laptop on void linux so im guessing there arent many choices for me in terms of aesthetics but im hoping anyone can help me finally settle down