将多个 C 源文件编译成唯一的目标文件 [英] Compile multiple C source fles into a unique object file

查看:31
本文介绍了将多个 C 源文件编译成唯一的目标文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 C 源文件,我正在使用 gcc.我基本上想编译所有这些并创建一个目标文件.当我尝试时:

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

我明白了:

gcc: cannot specify -o with -c or -S with multiple files

如果我尝试:

gcc -c src1.c src2.c src3.c

我得到三个不同的目标文件.如何告诉 gcc 编译所有文件以返回一个目标文件(我还想指定它的名称)?谢谢.

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).

如果你想合并编译的文件,通常使用 将它合并到一个静态库中ar 命令:

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

或将其作为带有 -l 标志的库链接

Or linking with it as a library with the -l flag

$ gcc file4.o -L. -lfoo -o myprogram

这篇关于将多个 C 源文件编译成唯一的目标文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆