top | item 37934700

(no title)

user8501 | 2 years ago

1. initialize all your variables - you will trip over this one, and it's always nasty

2. I typically throw a _ptr at then end for global pointers

3. use a unity build - create a build.c file and directly #include all .c files, and then just compile your build.c file. This will speed up compilation by many orders of magnitude, as well as allow the compiler to make better optimizations. Don't think too hard about how to separate your C files. I typically start in one file and I begin separating as themes or modules start to emerge. And even then, I wait a while, because I may change my mind. This allows my designs to become quite refined.

4. Make as few allocations as possible.

5. no comment

6. I get a personal kick out of sticking to C89, to my own detriment probably.

7. Errors are handled differently on a per function basis. But when an error requires a lot of cleanup, don't be afraid to use a GOTO.

8. Throw -fsanitize=undefined in there as well.

discuss

order

bluecalm|2 years ago

Initializing variables means the compiler will not be able to warn you when you use ununitialized value. I prefer to get the warning than use zero initialized one by accident.

Build.c file - good idea if performance is priority but you remove an option to get incremental builds (with make or the like).

I would add: read about warning options and enable as many as sensible ("-Wall -Wextra -pedantic from memory but there are a few others). Treat warnings seriously, don't allow them for longer than debugging/experimenting stage.

C99 has some useful features (like designated initializers or compound literals). Check if your compiler supports it.

__d|2 years ago

There's nothing wrong with sticking to C89, but honestly, stdint.h is hard to pass up. That said, you can define your own sized integers using the stdint names in about a few dozen lines, since you don't really want to be using most of the stuff in the standard version.

_benj|2 years ago

oh, I love the idea of making a build.c!

Specially because I came across a compiler (sdcc) that doesn't support multiple source files (everything should be compiled individually and then linked with main.c