我有两个文件,main.o
并且modules.o
,我正在尝试编译它们以便main.o
可以调用函数modules.o
.我被明确告知不要尝试#include module.o
.我真的不知道我应该做什么.我尝试了几个不同的版本gcc
(例如gcc -x c driver main.o modules.o
),但我没有得到任何工作:编译器不断返回
error: called object is not a function
Run Code Online (Sandbox Code Playgroud)
这些.o
文件是我的源代码文件(我被指示将我的源代码放在带扩展名的文件中.o
.)我该怎么做才能编译它?
Cro*_*man 24
如果您有两个源文件,则可以将它们编译为目标文件而不进行链接,如下所示:
gcc main.c -o main.o -c
gcc module.c -o module.o -c
Run Code Online (Sandbox Code Playgroud)
其中-c
标志告诉编译器停止编译阶段之后,不链接.然后,您可以将两个目标文件链接为:
gcc -o myprog main.o module.o
Run Code Online (Sandbox Code Playgroud)
这都是完全正常的行为,你通常会让makefile分别编译并链接它们,所以每次更改其中一个源文件时都不必重新编译每个源文件.
谈论main.o
"调用函数" module.o
是完全正常的,但.o
文件不是源文件,它是一个编译的目标文件.如果"将我的源代码放在带扩展名的文件中.o
"实际上意味着"将我的源代码编译成具有扩展名的文件.o
",那么这种情况会更有意义.
Man*_*dey 10
您应该定义要从中调用的函数modules.c
成main.c
成一个头文件,我们可以说modules.h
,和包括在头文件main.c
.获得头文件后,请将两个文件一起编译:gcc main.c modules.c -o output
另外两个笔记.首先,modules.o
是一个目标文件,它不应该包含在C源文件中.其次,我们不能有一个C文件有.o
扩展名.编译.o
文件时实际上应该出错.就像是:
$ cat t.o
int main() {
int x = 1;
return 0;
}
$
$ gcc t.o
ld: warning: in t.o, file is not of required architecture
Undefined symbols:
"_main", referenced from:
start in crt1.10.6.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
$
Run Code Online (Sandbox Code Playgroud)