Reputation: 1196
I am not understanding how I should compile with gcc the following .c and library.
example:
Files: "commons.h"
and "commons.c"
(the .c defines function etc...)
Files: "level1.h"
and "level1.c"
, level1.c
includes "commons.h"
Files: "level2.h"
and "level2.c"
, level2.c
includes "commons.h"
and "level1.h"
I tried this and got "undefined reference to x" (where x is a function inside level1):
gcc commons.c -c -o commons.o (OK)
gcc level1.c -c -o level1.o (OK)
gcc level2.c -o level2.o (error, undefined reference to x)
I expect to have level2 to be execute, I will only execute this.
How should I compile? Which order? (an example with command line will help me understand)
Upvotes: 0
Views: 72
Reputation: 22152
Your last line should also use the -c
flag in order to compile level2.c
to an object file level2.o
.
Afterwards the object files should be linked to create an executable, which is done via
gcc common.o level1.o level2.o -o my_executable
Alternatively you can directly supply all the source files to gcc
without the -c
flag, in which case it will perform all of the compilation and linking steps at once:
gcc common.c level1.c level2.c -o my_executable
Your error is currently caused, because you are instructing gcc
without the -c
option to compile and link the source file level2.c
alone, but of course it can not be linked alone as it is missing symbols from the other source files.
The fact that level2.c
contains main
does not change anything about this. main
is handled like any other function, only that it has a special meaning in the final executable as entry point.
Upvotes: 2