I have some C source files and I am using gcc
. I basically want to compile all of them and create one single object file. When I try:
gcc -c src1.c src2.c src3.c -o final.o
I get:
gcc: cannot specify -o with -c or -S with multiple files
If I try:
gcc -c src1.c src2.c src3.c
I get three different object files. How can I tell gcc
to compile all files to return one single object file (I also want to specify its name)? Thank you.
Maybe there is another more common approach to this, in this case please tell me.
You can't compile multiple source files into a single object file. An object file is the compiled result of a single source file and its headers (also known as a translation unit).
If you want to combine compiled files, it's usually combined into a static library using the ar
command:
$ ar cr libfoo.a file1.o file2.o file3.o
You can then use this static library when linking, either passing it directly as an object file:
$ gcc file4.o libfoo.a -o myprogram
Or linking with it as a library with the -l
flag
$ gcc file4.o -L. -lfoo -o myprogram
This is not a usual way to proceed, but you can easily achieve what you want by creating a new final.c
file with the following content.
#include "src1.c"
#include "src2.c"
#include "src3.c"
Then you can compile it as follows.
gcc -c final.c -o final.o
Note that there may be issues, read compilation errors, even if each file compiles successfully when compiled separately. This tend to happen especially with macro definitions and includes, when merging your source files into a single one this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With