r/C_Programming

What’s the usual way to handle a few platform specific functions in a portable C library?

I’m working on a small portable C library where only about five functions need to be implemented differently depending on the platform or the user’s needs. Three of them need to be overridden, while the other two could have weak default implementations.

At the moment I’m defining them as weak symbols and letting the application provide strong implementations. For such a small number of hooks, this seems convenient and keeps the API simple. I can see now that it’s not very obvious to the user that some of these functions are expected to be overridden.

Is using weak symbols like this a reasonable approach for a portable C library, or would something like a struct containing function pointers be more idiomatic? What is recommended?

reddit.com
u/mathlontrades — 16 hours ago

automating gcc install and usage

Hi, Im a 2nd year cs student. Ive had problems with installing the gcc compiler and remembering its flags between coding sessions. I also helped many 1st year students with it and almost always its a little too complicated for them. For that i built gccauto. it auto install and saves flags for compiling. Im not a pro programmer so if you have any tips or ideas pls share them. (some ai was used to help build it since im still learning)

its called gccauto on github. ubay-mostafa/gccauto

reddit.com
u/Friendly_Couple_2312 — 15 hours ago

a beginner in C, learning how to organize c files.

hello guys, I'm a beginner in programming, im self learning it while in college, im wondering how you C experts in C organize your code in files(to be exact, files as in file explorer), from small projects to big projects, i really want to learn how to organize, because i encountered this bottleneck when i learned python, but after being fed up of hiding a lot of abstractions, i decided to just jump on C to learn the fundamentals and really learn whats happening under the hood.

to give you context on my situation:

  1. i primarily use books for learning, i really dont use videos or any courses, unless its something like odin project, hence i dont really know how to organize files.

so to sum up:
i want to learn how you guys organize your c files from small projects to big projects.(in file explorer to be exact since im using windows for now).

reddit.com
u/PianistPrevious8637 — 1 day ago

Need explanations. I learn how to build simple CRUD app with C# and TS. I wanna really understand CS. So I tried to learn C but I get even more confused about many CS concepts.

I’m trying to learn C not just because I want to learn another programming language, but because I want to understand Computer Science and how computers actually work underneath the abstractions.

The problem is that I constantly fall into an endless chain of prerequisites/CS concepts

For example, I want to understand pointers:

int x = 10;
int *p = &x;

On the guide/website it says

>ointer is a variable that store memory address.

Okay, but then I ask:

  • What exactly is a memory address
    • address is where numbers telling where data is stored
  • What exactly is memory?
    • memory is where address live
  • Is memory the physical RAM?
    • etc... something with CPU
  • What exactly is RAM and CPU?
    • etc...
  • How does RAM actually work?
    • etcc..
  • What's the relationship between RAM, CPU, cache, virtual memory, thread, processing etc.?

And suddenly I'm 10 levels deep into computer architecture instead of learning pointers "*"😂

So what to do here, I wanna understand CS. I thought my experience with coding CRUD APP with C#, but no it doesn't help much

reddit.com
u/Wasabi-spicy00 — 1 day ago

I don't really understand why the K&R is this bad

Hi, maybe it was a stupid decision to learn C from the K&R book, but I am a CS student, and I have coded a lot with C#, Python, and other languages. It is true that I am not nearly a good programmer because we don't really study the important stuff here. We spend the time learning syntax instead of the critical things, but still, I do know what a variable, if statement, loop, and all that are. I also studied architecture, so I know how binary works, how two's complement works, how the sizes of variables can be different from one machine to another, and how data gets stored in memory, like endianness. I'm familiar with all that, and I am now at 2.7, type conversions, in the book.

So you would think that it is pretty easy, right? I mean, I literally just read stuff that I already know. It's just about how C deals with it. But no, fuck no. It is so ugly and random, it got me really pissed off. Like, I am genuinely mad about this.

I love writing down what I learn, like some kind of summary or something, and I tried to do this as well here, but I couldn't. I mean, I accept that the first chapter is just a tutorial. I enjoyed the programs there, and I tried typing all of them by myself. I even solved a lot of the exercises. But when Chapter 2 started, I expected it to be like, Oh, now we are diving deep inside the language. Since there is no other chapter with the same name, this is the only thing you're going to get about this particular part from the book.

But fuck, I was wrong. It is just so simplified to the point where you aren't learning anything. And you will say, Okay, your fault, bitch, it is a book for beginners, but not just that. It is like some guy wrote it down while trying to remember what he did. Like, that whole 2.7 part is what really got me pissed off. It is like there is no consistent topic or something. We're not going from one topic to another. It is just like some guy remembered, "Oh, I have to mention this," and then he says like two words about it and moves on to the next thing.

I don't even understand. Why didn't he just go from one topic to another after explaining it fully?

For example, it says, "In general, the only automatic conversions are those that convert a 'narrower' operand into a 'wider' operand."

Then, a line after this, he says, "Expressions that might lose information, like assigning a longer integer type to a shorter, or a floating-point type to an integer, may draw a warning, but they are not illegal."

After some research, I understood that, oh, he is first talking about arithmetic conversions, and now he is talking about assigning one type to another. I don't even know if this is really what he intended to say.

But it's not just that. Suddenly, now we're talking about converting uppercase to lowercase and what could go wrong. What does this have to do with type conversion? It's just manipulating the numeric value to get the character you want. There is no type conversion here.

But wait, he uses this to introduce us to a header, which I don't even know what it is, and he just randomly starts talking about it here, completely unrelated to the main topic. Then he talks about how some of its functions could return 0 and another number for true or false, not necessarily 1 or 0.

And I'm like, I can't. I just can't put this inside my head. How the fuck is all of this related to each other? I ended the chapter and I still don't know shit about conversions. It's all just some shitty information that you could probably just guess or learn through trial and error.

And before you get mad at me, this is not me saying, "Oh, this book is dumb." I am saying I don't understand what I did wrong that made me feel like everything is so random. Am I missing something here?

reddit.com
u/121df_frog — 1 day ago

How are functions in libm actually implemented ?

I'm trying to gather information for a school project about how elementary functions (exp, log, cos, sin, etc.) are implemented on computers, for maximum accuracy and efficiency.

I've already found some information about techniques that can be used to implement these functions, such as range reduction, Taylor series, polynomial approximations or minimax approximations. However, most of what I've found remains fairly theoretical, and I have no idea of what is actually used in the real world.

I tried to reverse-engineer the exp implementation in libm, but my knowledge of C and its intricacies is still fairly limited (though I'm working on improving it).

I'm particularly interested in understanding which approximation methods are actually used, how polynomial coefficients are chosen (Taylor, minimax/Remez, or other), and how implementations balance speed and accuracy.

But really, if you have any information whatsoever, it would be great.

If anyone has documentation, papers, or personal experience with this kind of subject, it would be really helpful.

Thanks in advance!

Edit : Thanks a lot to everyone ! You gave me exactly what I was looking for

reddit.com
u/New_Telephone926 — 2 days ago

Negative value in a pointer question.

Please look at this code. if i define the PTRTYPE as int, it stops working, while doing a uint, it does work...

void initILAPoll(debugBridge_t **d, PTRTYPE ptr){

`*d = (debugBridge_t *)ptr;`		`// base address of the DEBUG_BRIDGE peripheral`

`cb_init(cb, local_memory, bufferLength);`

`sprintf(xvcInfo, "xvcServer_v1.0:%d\n", MAX_WINDOW_SIZE);`

}

the usage in main code is done like this

`initILAPoll(&myD, 0x80000000);`

`//myD = (debugBridge_t *)0x80000000;`

where the variable myD is a structure pointer.

if i print the address of myD, it give the correct address. Moreover, the disassembly of the code is also the same in case of int and uint. Can somebody explain what behavior is at play here>

reddit.com
u/aliathar — 2 days ago

how to handle an input with two threads & ncurses?

I am making a monitor for one particular process, and I'm stuck on one problem with input handling.

As I said before I have a process monitor with two threads:

- data_worker: collects metrics

- UI thread (main): renders with ncurses

Both sleeping N seconds.

For example one of them

  while (global_running == 1) {
    cpu_worker(sh_st);
    ram_worker(sh_st);
    io_worker(sh_st);
    clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
  }

The UI has the similar structure, just calling ncurses rendering functions instead.

And I don't really know how to process the user input. Earlier I had an idea to create third thread that will process the input, but it kinda bad idea because of lovely ncurses is not thread safe, so this one the one reason why I stuck.

And because of this problem I realized that screwed up with code's architecture and don't really know to deal with it.

How do TUI tools typically handle the non blocking input loop alongside background data updates without breaking ncurses or causing race conditions on the shared data buffer? Any advices ?

reddit.com
u/TensaFlor — 1 day ago

Why do you use/don't use an IDE?

I've tried using a text editor with just the command line and for the most part isn't wasn't so bad until my game engine got big enough. Then I switched to Clion because it just handles so much more for big projects. Biggest thing is a visual debugger and easy refactoring that's C/C++ specific. Not to mention everything is setup out of the box.

I'm curious about other's reasons for using or not using an IDE.

reddit.com
u/AxeForge — 3 days ago

Not exactly C but the concept of the stack

I'm in my third year of happy C coding but I learned 6502 assembler in 1984 and now 70 years old. Therefore I often look at videos like: NES Mapper History to 1988 and Blaster Master Code Analysis - Talkin' Code Ep. 1

The mention of the stack made me think if the 6502 was had a bit of inspiration from C, but it was a lot older concept.

NES Mapper History to 1988 and Blaster Master Code Analysis - Talkin' Code Ep. 1

https://www.youtube.com/watch?v=EhO_iHkUkE0

https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

https://en.wikipedia.org/wiki/MOS_Technology_6502

u/grimvian — 2 days ago

What are your reasons for not using an IDE on a big project?

Earlier I made a post asking why people choose to use or don't use an IDE. I'm glad I got a lot of feedback on it and didn't start a new holy war.

But now I realize I should've been more specific. For big projects, why don't you use an IDE? As a 34 year old game programmer, I learned programming first with an IDE, code blocks and then visual studio.

I've tried doing vim, which is really good and fast in its own right, but I didn't want to deal with the learning curve. So then I went to sublime text, which again is really good and fast. But having to build your own workflow before you can even get started on the project itself.

I program my own game engine and games, which are pretty big projects. The tools that an IDE gives (Clion in my case) are just indispensable to me. Although I will say I have moments where it feels like it gets in my way.

reddit.com
u/AxeForge — 2 days ago

Simple dialogue system in C

Hello everyone. I'm working on a personal project where I'm porting a little game to C for learning purposes. It has very simple dialogue: it boils down to a few choices and a response on selecting a choice. There's the occasional conditional choice (and response), but that's all it is. My current approach has been as simple as it can be (see code below).

However, I'd like to ask for help with supporting translations, i.e. allow for a way to let outside users add a translation in any way. (You can imagine someone translating in a csv, or json, or C directly). I want to add a way to do so, but I can't figure out a good way to do so. (English will be the base language, so for all intents and purposes it being stored inside dialogue.c is fine for now).

Thanks in advance! :)

static const DialogueChoices CHOICES = { 
  .count = 1,
  .options = {
    {  
       .choice = "Choice goes here", 
       .response = "Response goes here"
    }
}

// switch over character id and return the appropriate DialogueChoices struct
DialogueChoices get_dialogue_choices(CharacterId id);
reddit.com
u/ZookeepergameFew6406 — 2 days ago

TIL glibc lets you add custom ((v)f)printf format specifiers.

I had a need for an extended printf, and found that rather than writing my own, glibc lets you register your own specifiers with register_printf_specifier.

I made a simple demo for printing bool as it kind of annoys me to have to type printf("%s", value ? "true" : "false"), and I don't like using integers to represent booleans. (This wasn't my goal, but it's the simplest type to demonstrate).

Now can type printf("%?", value) to print true or false. Works will all the *printf style functions.

Has an alt (#) representation, which is uppercase TRUE or FALSE - ie: "%#?".

And I also added width specifiers for easy alignment. You can specify some padding with "%n?" - right aligned by default, with "%-n?" aligning left. Could probably extend to support * also with extra argument for width.

Demo in godbolt

Just thought others may find this interesting.

EDIT : Have been corrected and this also works with *sprintf functions.

u/WittyStick — 4 days ago

How do I solve problems without using AI

Hello guys. I am attempting to learn how to code again but without the use of AI this time.

How do you attempt a problem or understand a solution without using AI for help.

For example, I wanted to build a small calculator to remind myself of the basics of C. I had a problem where my scanf was not outputting the desired result. 

The program had something like this:

int x, y;
printf("Enter two operators: ");
scanf("%d", &x);
scanf("%d", &y);
printf("x: %d, y: %d", x, y);

My inputs would be 10 & maybe 2, but the output would be 10 & 0, in some cases 0 and nothing for y.

I was able to get through this by just using one scanf:

scanf(“%lf %lf”, &x, &y);

But I still do not understand why that happened and through my google search, could not find anything that explained it well. The problem might also be that I cannot explain the problems I come across clearly, so I might not be able to find an answer through google.

So my question is, how do you guys go through problems like these where you can’t find a post where someone had a similar problem and had been told what to do to solve the problem without defaulting to AI.

Excuse my writing - I am trying to learn how to type without letting AI revise my sentences.

reddit.com
u/Either-Suggestion400 — 4 days ago

What is the back end and the front end heap allocator on linux?

I've been able to find very little information which concerns the front end and back end allocator on linux. The few articles which I have found discussing front end and back end allocators haven't really done a good job of explaining what a front end and a back end allocator is on linux.

reddit.com
u/FewMolasses7496 — 3 days ago

Presenting CBlockAlloc: a WIP personal project

Hello everyone,

Yesterday, I started a project that I find super interesting. I first thought of it because I saw many people who were trying to do things with the stack only because "dynamic allocation is slow". The main point for why they consider it slow and heavy is that a program needs to talk directly to the OS to allocate memory. However I saw some people propose a solution: allocate once a big chunk of memory that you will use for all your "dynamic" allocations, which makes it way faster because you only need to make a syscall once at the start of the program. I've thus decided to create a library that does just that, and can be called through an API that "simulates" the normal function calls such as malloc() or realloc(). I've been working on it since yesterday, and it's been a lot of fun! it's not ready at all yet, but right now it's looking good. Also, I'm looking for some feedback:

How good is my code for now? Would you do some things differently? Also, would YOU use such a library? What would you expect from a library like that?

Thank you very much for your time, my github profile is Koda-be (I can't send the link to the report because not enough stars and too young).

Also, how could I test my code? I don't really know what to do to test it right now, so...

No AI has been used nor will it be used in this project.

Also, I licensed it under MIT but do I need to do something else? I simply chose a license when creating the REPO, and I don't know much about copyright laws...

reddit.com
u/Koda_be — 4 days ago

Help me in building VM without KVM in C

Hello everyone! Recently i am started coding my own VM on the C language. I am using mmap and creating a new process with isolation from the host (my system) like syscalls, memory access. However, I ran into a problem: How to restrict VM access (guest proccess, mmap) to the host memory. I am really don`t know how to do that. Can anyone help me with that case?

reddit.com
u/savaw2 — 3 days ago

Compressing executables (upx)

Hola,

I'm currently in the final stages of finishing the first version of a game I made using raylib. I ended up with a single statically linked binary containing all the assets. I found a tool called upx which can compress executables. I tried it on Windows, and it reduced the size of my exe by more than half and it still runs without any noticeable difference.

My question is, has anybody here experience with this? Are there any downsides to consider?

cheers!

reddit.com
u/stiggg — 4 days ago

Presenting my current WIP project: CBlockAlloc!

Hello everyone,

Yesterday, I started a project that I find super interesting. I first thought of it because I saw many people who were trying to do things with the stack only because "dynamic allocation is slow". The main point for why they consider it slow and heavy is that a program needs to talk directly to the OS to allocate memory. However I saw some people propose a solution: allocate once a big chunk of memory that you will use for all your "dynamic" allocations, which makes it way faster because you only need to make a syscall once at the start of the program. I've thus decided to create a library that does just that, and can be called through an API that "simulates" the normal function calls such as malloc() or realloc(). I've been working on it since yesterday, and it's been a lot of fun! it's not ready at all yet, but right now it's looking good. Also, I'm looking for some feedback:

How good is my code for now? Would you do some things differently? Also, would YOU use such a library? What would you expect from a library like that?

Thank you very much for your time, here's the link to the repo: https://github.com/Koda-be/CBlockAlloc

Also, how could I test my code? I don't really know what to do to test it right now, so...

No AI has been used nor will it be used in this project.

Edit: also, I licensed it under MIT but do I need to do something else? I simply chose a license when creating the REPO, and I don't know much about copyright laws...

u/Koda_be — 4 days ago