问题描述
我遇到以下错误,无法终生发现自己在做错什么.
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.");
}
现在,如果我将整个函数包括在头文件中,而不仅仅是签名,它就可以正常工作,所以我知道其中包括了wtf.h.为什么编译器看不到wtf.c?还是我错过了什么?
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?
致谢.
推荐答案
您需要将wtf
与您的main
链接.一起编译的最简单方法-gcc
将为您链接'em,如下所示:
You need to link wtf
with your main
. Easiest way to compile it together - gcc
will link 'em for you, like this:
gcc main.c wtf.c -o main
更长的方式(wtf
的单独编译):
Longer way (separate compilation of wtf
):
gcc -c wtf.c
gcc main.c wtf.o -o main
更长(单独的编译和链接)
Even longer (separate compilation and linking)
gcc -c wtf.c
gcc -c main.c
gcc main.o wtf.o -o main
您可以直接运行ld
,而不会影响上一个gcc
调用.
Instead of last gcc
call you can run ld
directly with the same effect.
这篇关于使用头文件时出现未定义的符号错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!