Reputation: 33
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 :)
Upvotes: 3
Views: 131
Reputation: 21
The error You're getting is because of wrong path to those header files. Before selecting "includes" folder you should go one folder back to access it (e.g. #include "../includes/functions.h"
). In your case some kind of build system would be useful to make whole process of compilation easier. You can try Makefile, CMake or even premake5 for some extra convenience.
Additionally: You should avoid such complex paths in the include "some/path"
as this can lead to hard to find errors later in development process. That is when the build system comes with great help.
Upvotes: 1
Reputation: 2447
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.
Upvotes: 8