Whenever we create a file with custom function definitions, say utils.c
and its corresponding header file utils.h
containing the function declarations. I have to compile the utils.c
file along with the driver code that I am using it in, with a command like gcc driver.c utils.c -o my_exe
.
So what instruction compiles the standard C files, whose header files we include like stdio.h
?
Compiling is a three step process. Preprocessing, Compilation and Linking.
gcc driver.c utils.c -o my_exe
is short hand for:
gcc -c driver.c -o driver.o
gcc -c utils.c -o utils.o
ld driver.o utils.o -o my_exe
Which is compile driver, compile utils and then link everything together.
Recompilation is still missing in our example. The includes is copied into the c files for compilation. The following steps breaks it up even further to show the preprocessing that handles the code in the header files:
gcc -E driver.c -o driver.i
gcc driver.i -o driver.o
gcc -E utils.c > utils.i
gcc utils.i -o utils.o
ld driver.o utils.o -o my_exe
gcc driver.o utils.o -o my_exe
can also be changed include libraries with for example -lm
to include standard math library (libm.a or libm.so). Libraries is just precompiled c source code (object code or .o
) in a container file.
The standard libraries (as in stdlib.h
and stdio.h
) is libc.so
(or libc.a
). You do not need to link them in explicitly but you can if you want to.
Then gcc driver.o utils.o -o my_exe
becomes gcc driver.o utils.o -o my_exe -lc
You can precompile your code in the same manner for later linking:
gcc -c utils.c -o utils.o
ar rcs libUtils.a utils.o
gcc driver.c -L. -lUtils -o my_exe