使用头文件时出现未定义符号错误
我收到以下错误,并且我一生都无法弄清楚我做错了什么。
$ gcc main.c -o main
Undefined symbols:
"_wtf", referenced from:
_main in ccu2Qr2V.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
main.c:
#include <stdio.h>
#include "wtf.h"
main(){
wtf();
}
wtf.h:
void wtf();
wtf.c:
void wtf(){
printf("I never see the light of day.");
}
现在,如果我在头文件中包含整个函数而不仅仅是签名,它符合要求,所以我知道 wtf.h 已被包含在内。为什么编译器看不到 wtf.c?或者我错过了什么?
问候。
I'm getting the following error and can't for the life of me figure out what I'm doing wrong.
$ gcc main.c -o main
Undefined symbols:
"_wtf", referenced from:
_main in ccu2Qr2V.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
main.c:
#include <stdio.h>
#include "wtf.h"
main(){
wtf();
}
wtf.h:
void wtf();
wtf.c:
void wtf(){
printf("I never see the light of day.");
}
Now, if I include the entire function in the header file instead of just the signature, it complies fine so I know wtf.h is being included. Why doesn't the compiler see wtf.c? Or am I missing something?
Regards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将
wtf
与您的main
链接。一起编译它的最简单方法 -gcc
将为您链接它们,如下所示:的方法(单独编译 wtf):
甚至更长(单独编译和链接)
更长 最后一次调用 gcc 时,您可以直接运行 ld 以获得相同的效果。
You need to link
wtf
with yourmain
. Easiest way to compile it together -gcc
will link 'em for you, like this:Longer way (separate compilation of
wtf
):Even longer (separate compilation and linking)
Instead of last
gcc
call you can runld
directly with the same effect.您忽略了这样一个事实:仅包含标头并不会告诉编译器有关标头中声明的内容的实际实现(定义)在哪里的任何信息。
它们可能位于执行包含的文件旁边的 C 文件中,它们可能来自预编译的静态链接库,或者系统链接器在读取可执行文件时加载的动态库,或者它们可能来自运行时用户程序员控制的显式动态加载(
dlopen()例如,Linux 中的函数系列)。
C 不像 Java,没有隐含的规则,仅仅因为 C 文件包含某个标头,编译器也应该做一些事情来“神奇地”找到标头中声明的东西的实现。你需要告诉它。
You are missing the fact that merely including a header doesn't tell the compiler anything about where the actual implementation (the definitions) of the things declared in the header are.
They could be in a C file next to the one doing the include, they could come from a pre-compiled static link library, or a dynamic library loaded by the system linker when reading your executable, or they could come at run-time user programmer-controlled explicit dynamic loading (the
dlopen()
family of function in Linux, for instance).C is not like Java, there is no implicit rule that just because a C file includes a certain header, the compiler should also do something to "magically" find the implementation of the things declared in the header. You need to tell it.