我想在几个文件之间共享一些功能实现
更具体地说,我希望 file1.c 和 file2.c 能够使用相同的功能(而不仅仅是复制粘贴解决方案),调用它的 FUNC()即可。
所以我拥有的是:
file1:
#include"shared.h"
int main() {
int x=func();
}
file2:
#include"shared.h"
int main() {
int y=func();
}
shared.h:
extern int func();
shared.c:
#include"Shared.h"
int func() {
// some implementation here
}
当我尝试使用gcc file1.c
编译它时,我得到“未定义的引用'func()'”......
我如何使它工作?
答案 0 :(得分:3)
您需要编译目标文件,然后链接它们,只有链接器才会检查引用:
gcc shared.c -c
gcc file1.c -c
gcc file2.c -c
gcc file1.o shared.o -o program1
gcc file2.o shared.o -o program2
答案 1 :(得分:2)
Gcc Linker正在寻找func()的实现。您可以指定多个* .c文件作为gcc的输入,链接器将在生成的目标文件中搜索func()。
gcc file1.c shared.c
答案 2 :(得分:0)
您还需要编译shared.c