Search code examples
cincludedirectory-structure

is this the right way to use Includes in C?


I was trying to organize my previously done C project (Uni project), I used Header files at then, but now i wanted to make it more clean, so went on dividing it into directories. But...

Help me..

directory structure:

project/
├── includes/
│   ├── functions.h
│   └── flats.h
└── src/
    ├── main.c
    └── functions.c

#include "includes/flats.h"
#include "includes/functions.h"

and I've tried running:

gcc -Iincludes src/main.c src/functions.c -o main -lm

gcc -o main src/main.c src/functions.c -Iincludes -lm

gcc -o main src/main.c src/functions.c -lm

and i'm getting-


src/main.c:4:10: fatal error: includes/functions.h: No such file or directory
    4 | #include "includes/functions.h"
      |          ^~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
src/functions.c:5:10: fatal error: includes/flats.h: No such file or directory
    5 | #include "includes/flats.h"
      |          ^~~~~~~~~~~~~~~~~~
compilation terminated.

actually, it was solved when i used absolute paths instead of relative. But, its not a better way right?

If there are any other ways, please help me. Thanks...

FOUND THE ANSWER (from comments ofc):

Using #include "../includes/flats.h" & #include "../includes/functions.h" works! with al the run commands i've mentioned above

Updated:

Above approach is not preferred since, its not flexible, for instance if u change or rework on your directories, you'll have to come back and change the includes again and again...

Before I used

#include "includes/flats.h"
#include "includes/functions.h"

also, tried to use gcc -Iincludes src/main.c src/functions.c -o main -lm

which just tells, the compiler to look for /includes/includes/flats.h

so, I'm supposed to just use

#include "flats.h"
#include "functions.h"

and

gcc -Iincludes src/main.c src/functions.c -o main -lm

-I tells the compiler to check includes folder for includes...

Thanks again for clarification with explaining :)


Solution

  • Use -Iincludes with the compiler and #include "header.h" (without the includes/ prefix) in your source files.

    Compile with:

    gcc -Iincludes src/main.c src/functions.c -o main -lm
    

    This tells the compiler to look in the includes directory for headers, and the #include directives then correctly find them. This is the standard and most flexible approach.