Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips/resources for structuring C code? [closed]

Does anyone have tips/resources for how to, in the best way, structure your C code projects? (Different folders etc.) And how do you know when it's good to split code into separate files? And what is an example of a good Makefile?

My project is not that big, but I wanna start to structure my code at an early stage..

like image 686
Eivind Avatar asked Aug 22 '26 02:08

Eivind


2 Answers

Structuring code needs some experience but mostly common sense.

For splitting code, you usually go for readability: conceptually coherent functions/datatypes should go in the same file. You can take c standard library as a good example. It is better to keep your data structure definitions and function declarations in separate headers. This allows you to use the data structures as part of a compilation unit even if you have not defined all the functions.

Files that provide similar functionality should go in the same directory. It is good to avoid deep directory structure (1 level deep is best) as that complicates building the project unnecessarily.

I think Makefiles are OK for small projects, but become unwieldy for bigger ones. For really serious work (if you want to distribute your code, create an installer etc) you may want to look at cmake, scons, etc.

Have a look at the GNU coding standards: http://www.gnu.org/prep/standards/standards.html

Look at the gnu make manual for a simple example Makefile. You can also pick up any opensource project and look at the Makefile. Browsing code repositories in sourceforge.net may be useful.

like image 167
subhacom Avatar answered Aug 23 '26 16:08

subhacom


Read one of the many C coding standards available on the internet and follow one that looks reasonable for your requirements. A few links:

  • GNU Coding Standards
  • C Coding Standards at IRAM (pdf)
  • Indian Hill C Style and Coding Standards

The following books also contain effective guidelines on writing good C code:

  • The C Programming Language
  • The Practice of Programming
  • The Elements of Programming Style
like image 36
Vijay Mathew Avatar answered Aug 23 '26 17:08

Vijay Mathew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!