Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

gcc - Compile multiple C source fles into a unique object file

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...