Search code examples
cincludec-preprocessorcode-organization

How to properly split a C program in files and include then?


I organized my program splitting every entity in its own file. Which is something like this.

main.c

#include "student.h"
#include "subject.h"
#include "classroom.h"

#define PI 3.14
int sum(int a, int b);

student.h

typedef struct st student;

student.c

#include "student.h"

subject.h

typedef struct sb subject;

subject.c

#include "subject.h"

classroom.h

typedef struct cr classroom;

classroom.c

#include "classroom.h"

My problem is, inside classroom I need student and subject. How should I include this? should I include this inside classroom.h or classroom.c?

#include "student.h"
#include "subject.h"

Second, I have things on main.c that are used by all of then like sum() and PI

How it is the right way including implementation in the header or including header in the implementation file? and should I include the header or implementation files?

If I throw everything on a single file it compiles just fine, but I'm not doing this right it does not compile.


Solution

  • So the organisation of "x.h" and "x.c" (or "x.cpp") is a fairly standard way to do things. But some things don't fit in there, and sometimes you need a "constants.h" or some other name for things like PI and SpeedOfLight.

    Something like sum would fit nicely into a "utils.h" - whether you have enough to make it worth having a "utils.c"

    Your .c file should include all header files that it needs (but no more).

    For example:

    #ifndef X_H__
    #define X_H__
     ...  
     all the contents of x.h goes here 
     ... 
    #endif
    

    And header files should include all things THEY need themselves. So for example, if "x.h" needs "a.h" and "b.h", there should be #include "a.h" and #include "b.h" in "x.h" so you don't have to remember that:

    If I include "x.h", I must put "a.h" and "b.h" before it.

    At the same time, don't add more includes than you actually need...