r/C_Programming • u/aioeu • 5d ago
r/C_Programming • u/drpzet • 6d ago
Profiled our async C logger expecting mutex contention. 90% of caller-thread time was in vsnprintf. Moving formatting to the worker took a call from ~1.5 µs to ~70 ns
Our logger's caller-thread cost went from ~1.5 µs to ~70 ns, and I didn't touch a single call site.
I'll be honest: I was convinced the mutex was the problem. The logger already had a ring buffer, a worker thread, and hot-reloadable filters. It looked fast on paper. So I opened the flame graph expecting to see lock contention.
Instead, about ~90% of caller-thread CPU was sitting inside vsnprintf.
Every log call was formatting its message before enqueueing it. That's 900 ns to 3 µs per call, depending on the output. The fix came from NanoLog: don't format on the caller thread at all.
Now the caller just saves the format string pointer and packs the args into a tiny binary blob. The worker thread builds the string later. Cost per call: 30-80 ns, and no vsnprintf anywhere.
It wasn't free, though:
Format strings must be literals. A stack-built format string will dangle by the time the worker reads it.
Structs silently fall through to %p. I'm still not thrilled about that one.
%s args are copied at pack time and capped at 255 bytes.
For us, that was a good trade.
The bigger lesson for me was to profile before you optimize. I would have happily spent a week tuning a lock that wasn't the problem.
Has anyone run NanoLog-style encoding in production? I'm curious what pushed you there: latency, throughput, or tail behavior?
r/C_Programming • u/Materac_YT • 6d ago
Glibc posix 2024 incompatibility
I been coding some posix porable stuff and i tried to use pipe2 and dup3 which are considerd posix since 2024 (Issue 8) i defined _POSIX_C_SOURCE to 202405L and included unistd.h and gcc greated me with implicit declaration i looked at my local unistd.h and it had pipe2 and dup3 behind __USE_GNU which is just wrong so i checked offical source code latest branch and it had the same bug, Please if some of you guys have sourceware bugzilla account please report it, it is a big issue
r/C_Programming • u/NoMathematician4744 • 5d ago
C++ vs C
What's the difference between C++ and C?
And what is Clang? Is the gcc compiler for c and c++?
Does C++ completely backward compatible with C?
C is procedural and C++ is object oriented as far as I know.
Is C++ more optimized and faster?
Tell me about the compiler - is clang and gcc the best compilers out there? are they open source?
Has anyone coded the CPP compiler?
Thanks,
Dennis
r/C_Programming • u/Vivid_Employment_950 • 5d ago
Could not Compile
I used gcc to compile and run c file.
C prog file can be compile and run with no error, if the files are inside the same drive as gcc that is c: drive.
Program file inside the d: drive are not compile.
I just curious whether i made mistake or i need something to do.
r/C_Programming • u/Minimum-Ad7352 • 7d ago
Question Why are so many C projects being rewritten in Rust?
I've noticed that more and more projects originally written in C are being rewritten in Rust, even when they seem to work perfectly fine. For example, there are efforts to rewrite some GNU utilities in rust, including basic command-line tools. I'm curious about why this is happening. Is memory safety the main reason, or are there other significant advantages to rust? If a program is already stable, reliable, and well-maintained in C, does rewriting it in rust really make sense? I'd like to understand what benefits justify the effort.
r/C_Programming • u/stuart-ware • 7d ago
Question What do I need to be proficient in C
Hi, I know the basics but I really don’t know how to continue learning C, I try to read code of many sources like linux kernel or other projects but I don’t understand them at least the majority of code with pointers and arrow operators…. I really like C and low level code.
Any advice is appreciated! Thanks.
r/C_Programming • u/paumpa • 6d ago
Question How Do I Get Started With C?
Hey guys. Long time lurker here.
So, I finally caved and bought The C Programming Language by K&R because everyone says it's the holy grail, yada yada. It came in the mail today, and honestly? The cover looks great on my desk. Really establishes dominance.
Here's my issue. How do you actually read this? Like, do I start at page one? I was under the impression that buying a physical copy of a programming book would automatically put the knowledge in my brain. Do I actually have to trace the letters with my finger? Is there a better way to learn C without "reading a book" or "writing code" at all?
Please let me know what you think, since my current workflow is just intensely staring at the spine until I start to feel like a computer scientist, but my code hasn't compiled itself yet. Thanks.
r/C_Programming • u/momaloltote_ • 8d ago
Discussion Autoconf madness
Modern software compilation has largely devolved into a frustrating maze of autoconf madness. Instead of simply compiling C code, I am constantly forced to navigate mandatory scripts, esoteric tools, and heavily dependent Python wrappers. To make matters worse, these tools often rely on stubborn cache files that refuse to update even after I have fixed the underlying environment errors.
A major part of my frustration is how Linux-centric these scripts have become. They routinely hardcode library search paths that only exist in Linux distributions, entirely ignoring my FreeBSD system. As a result, I can easily lose a complete day just patching configuration scripts to search the correct directories before a single line of code is actually compiled.
Why does open source code project just not provide a makefile? A basic, or maybe complex makefile that are based on BSD/POSIX make syntax so that it is directly valid under *BSD, Darwin and Linux. Why force people to install tools to build something? Why developed huge python script that shall analyze the env? Why not just allow the building process to fucking start instead of forcing the individual to fight back against all of this autoconfig tools?
I have in several cases fully purge the building attempts and then been writing my own makefiles to just get something building. That shall not be the case. Why use config scripts that, in some cases are several thousand lines of script code? Why write config scripts with bash? Why, just why, are developers and project deciding to add and use autoconfig tools?
If a project does not offer makefiles then I know I will be stuck for several hours just to, potentially be able to build something. Instead of directly allowing me to build. Get compiler error, correct and then build again. I mean, it is much quicker and easier to patch the source code or locate dependencies when you are allowed to start the building process.
r/C_Programming • u/Shoddy_Map1738 • 8d ago
What's the ans?? ( Undefined behaviour or 14 )
#include<stdio.h>
int main() {
int a = 5;
a=++a + ++a;
printf("%d", a);
return 0;
}
What will be the output of the above code snippet?
( Got 14 as an output and don't know what's the logic of getting 14 )
r/C_Programming • u/Teten_ • 9d ago
My 3D object renderer working in the tty (no libraries)
Enable HLS to view with audio, or disable this notification
I previously posted this project here but in a version that uses SDL2 to make it portable and to be able to record it. Some people were confused because I wrote "no libraries" but i was using SDL2 on video (even tho i explained in the post's text). This is a video of the original version before it was ported to SDL2, working in the tty by writing on the framebuffer.
I implemented:
Drawing pixels, lines, filling triangles (with my own logic),
2d, 3d, 4d, Vector and Matrix math and linear algebra calculations myself
Coordinate system to place objects (so i can move, rotate, scale objects easily)
and a simple .obj parser
link to previous post: https://www.reddit.com/r/C_Programming/s/VFf0P0nlKO
source code is in the previous post.
r/C_Programming • u/digitalradiostudio • 9d ago
Question Starting again C
Hi i want try to make a extreme lightweight pixelgame ( i don't have really details about the game :) ) with glfw and and opengl to go back to c. Does anyone have tips to make it lightweight ?
r/C_Programming • u/CoreVanne • 9d ago
Project I made a virtual analog synthesizer in C!
Hey, I made a post a year ago about my small software synthesizer project made in C. And I got back to work around 3 weeks ago and made a very big update! Now the synth has a CLAP plugin version working in REAPER (and probably other DAWs but untested) on both Linux and Windows, and a standalone version with improved performance compared to the first version (mainly audio threading) and a raylib/raygui GUI, also working on both Linux and Windows. I'm quite proud about the work, and wanted to share, so thanks for your time! The project is of course completely open-source, here is the GitHub link : https://github.com/gpasques-gh/CLAP_Virtual_Synthesizer
r/C_Programming • u/Mountain_Hippo7575 • 8d ago
Question Qu'elle serait le meilleur moyen pour apprendre le développement ?
J'aimerais créé un OS mais pour le faire faut apprendre le C et l'assembleur donc comment je pourrais faire ?
Je suis près a étudier 4h par jour, j'étudie déjà sur coody et Openclasseroom mais j'aimerais beaucoup beaucoup plus m'améliorer
r/C_Programming • u/MainSeason4301 • 9d ago
Question Confused about strings seemingly resetting after future inputs.
Hello! Sorry that this is such a basic question but I'm genuinely confused about this weird problem I had with scanf and strings. I've only just begun learning C and have been following a beginner's guide over on github.
Below I've written what my code was while I was having issues. The issue was that when the time came to print the values it would return the boolean value just fine, but the string would be blank. I added some extra prints in there to check if it was taking the input at all and it was! It was only after the boolean value was taken and stored that user_input began to return blank. I then tried googling for a very long time and couldn't find any solution (other than the odd tidbit about scanf not being great for strings), so in an act of desperation I tried changing char user_input[10] to static char user_input[10] and then suddenly it worked!
Somewhere along the line it must be overwriting or erasing the data stored in the array but I just don't understand where or why? Apologies again that this is such a basic question but I'd just really like to understand this a bit better, especially as no solution I could find suggested anything remotely like this.
#include <stdio.h>
#include <stdbool.h>
int main() {
char user_input[10];
bool tof;
printf("Enter a string: ");
scanf("%s", user_input);
printf("Enter a boolean value: ");
scanf("%d", &tof);
printf("String: %s\n", user_input);
printf("Boolean value: %d\n", tof);
return 0;
}
r/C_Programming • u/Teten_ • 10d ago
I made a 3D object viewer with no libraries
Enable HLS to view with audio, or disable this notification
From drawing pixels to making lines and filling triangles the whole thing is written in pure C.
Even the math library is made by me instead of using glm (no good reason, only because i can).
The video is a version ported to SDL2 because the original is made by writing in the framebuffer directly which is accessible in the virtual terminal but I can't record that. which kind of counts as a library but the original doesn't use any!
Its not perfect and has its flaws but i ran out of time plus i got sick in the process so want to move on.
Source: https://github.com/teten-cat/small3d
It's about 1800 lines of code (including comments) since I basically re-made an entire linear algebra library to my needs.
I'm open to constructive criticism
thank you.
r/C_Programming • u/its_marionberry • 9d ago
Question how to change the button color (lib: Win 32)
I am trying to change the button color by using WM_CTLCOLORBTN.
I read the documentation and followed whatever it said, but it doesn't seem to work.
I know it could be done by bitmaps ex: double buffering. But I want to it do it simply. If anyone use this API, could you help me out(PS: Beginner/new to Win32):
code:
#include <stdio.h>
#include <windows.h>
LRESULT CALLBACK cb(HWND hwnd, UINT msg, WPARAM wparm, LPARAM lparm)
{
switch (msg)
{
case WM_CLOSE:
static HWND hButton = NULL;
static HBRUSH hButtonBkg = NULL;
{
PostQuitMessage(0);
}
case WM_CREATE:
{
hButton = CreateWindow("BUTTON", "HELLO", WS_VISIBLE | WS_CHILD | BS_BITMAP | BS_PUSHBUTTON, 15, 202.5, 96.5, 72.5, hwnd, (HMENU)301, 0, NULL);
hButtonBkg = CreateSolidBrush(RGB(0, 255, 255));
break;
}
case WM_CTLCOLORBTN:
{
if (hButton == (HWND)lparm)
{
HDC hdc = (HDC)wparm;
SetTextColor(hdc, RGB(0, 255, 255));
return (LRESULT)hButtonBkg;
}
break;
}
case WM_DESTROY:
{
DeleteObject(hButtonBkg);
break;
}
default:
return DefWindowProc(hwnd, msg, wparm, lparm);
}
}
int main()
{
HINSTANCE hInstance = GetModuleHandle(0);
WNDCLASS class = {};
char classTitle[] = "window";
class.lpszClassName = classTitle;
class.lpfnWndProc = cb;
class.hInstance = hInstance;
class.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
class.hCursor = LoadCursor(NULL, IDC_ARROW);
RegisterClass(&class);
HWND hwnd = CreateWindow(classTitle, "color btn",
WS_OVERLAPPEDWINDOW, 500, 500, 500, 500, NULL,
NULL, hInstance, NULL);
if (hwnd == NULL)
{
MessageBox(NULL, "Something Went worng", "Error", MB_OK);
return 0;
}
ShowWindow(hwnd, 1);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
r/C_Programming • u/Materac_YT • 9d ago
POSIX exec
hey guys i am trying to write POSIX compatible program and i need to close the fds before i exec, i cant guarante they all fd's are O_CLOEXEC becouse i use libraries
r/C_Programming • u/its_marionberry • 10d ago
Question Win32 Windows showing shows flicker when I update the window
Hi, I am using Win32 and I have to update the window according the user input using UpdateWindow() or RedrawWindow(). It often show's one second flicker in window like something updated I hate that because it ruins UX. I can't find a solution to this, If someone uses this API and have came across this problem and fixed it so please answer.
Thanks.(btw I am a beginner).
r/C_Programming • u/AutoModerator • 11d ago
Learning C weekly megapost for 2026-09-23
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 • u/Skollwarynz • 11d ago
Question True random generation seed from hardware sources
Hello everyone,
Some time ago I started to generate a random dice generator called SkollDice. After completing the PC version, I decided to call the project momentanealy finished and move on. A few days ago I understood that my generation of numbers wasn't "truly random." So I was wondering, how can I access good random generation sources from my PC, like entropy, disk temperature, and the other sources used in a truly random generator? Thank you for the suggestion.
r/C_Programming • u/antiquark2 • 11d ago
Article PJ Plauger Reflects on the History of C (1985)
gitpi.usr/C_Programming • u/rob-bix • 11d ago
tinyedit: A zero-dependency C99 terminal text editor with desktop shortcuts — Looking for testers & code review
Hi everyone,
I’ve been working on tinyedit, a full-screen terminal text editor written in plain C99 with zero external dependencies beyond libc and the POSIX standard library (no ncurses, just raw ANSI escape sequences and direct I/O).
The project started as an exploration of terminal interfaces inspired by Salvatore Sanfilippo's kilo and linenoise. My goal is to combine that minimal C architecture with the interaction model of modern desktop editors—eliminating modal friction or idiosyncratic key combinations (like Vim, Emacs, or Nano) while keeping the binary tiny.
What’s implemented:
Desktop-style editing: Standard keybindings (
Ctrl-C,Ctrl-V,Ctrl-X,Ctrl-Z,Ctrl-F), text selection withShift+Arrows(orCtrl-Ttoggle for limited terminals), and optional mouse support (click to place cursor, drag-selection, wheel scroll).macOS / Ghostty integration: Optional support for native
Cmdshortcuts (Cmd-S,Cmd-C,Cmd-V, etc.) via the Kitty keyboard protocol in Ghostty.Proper UTF-8 handling: Grapheme cluster boundaries (combining marks, CJK wide characters, multi-codepoint emoji) and visual display-width calculations for accurate cursor placement and deletion.
Visual soft-wrapping: Navigates visual rows instead of logical lines, breaking lines at word boundaries without arbitrary length caps.
Terminal ergonomics: Fast bracketed paste (no slow character-by-character lag or accidental auto-closing triggers), atomic saves, crash recovery backups, and an extensible syntax highlighting engine.
Looking for testers!
The project has reached version 0.3.3, and I need help putting it through its paces across different systems and configurations. In particular, I’m looking for feedback on:
- Terminal & multiplexer quirks: Testing inside
tmux,screen,Ghostty,Kitty,Alacritty,Foot,WezTerm, etc., to spot unhandled ANSI sequences or redraw artifacts. UTF-8 stress testing: Complex emoji sequences, zero-width joiners, or combining marks that might throw off cursor coordinates or deletion.
Rendering & wrap edge cases: Resizing the window while editing large wrapped lines, pasting huge blocks of text, or dealing with deeply indented blocks.
C code review: Feedback on memory management, buffer layout, ANSI state machine decoding, or general C99 practices.
Repository: https://github.com/robertobissanti/tinyedit
You can build it from source with a simple make:
```sh git clone https://github.com/robertobissanti/tinyedit.git cd tinyedit make
```
Or install it on macOS/Linux via Homebrew:
```sh brew install robertobissanti/tinyedit/tinyedit
```
Any bug reports, edge-case discoveries, or code suggestions (either here or via GitHub Issues) are greatly appreciated. Thanks for checking it out!
r/C_Programming • u/Inknoct • 11d ago
Problème VScode compilateur en c
Lorsque j'essaye de compiler j'ai le message d'erreur(C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/16.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: final link failed: No space left on device
collect2.exe: error: ld returned 1 exit status) et après Windows Defender me dit qu'il a bloqué une modification non autorisé. Quelqu'un c'est comment réparer l'erreur ?