关于重复符号的奇怪 ld 错误
我有一个由两个文件组成的项目,main.c 和 logoff.c。 当我尝试编译它们时,出现此错误:
gcc -c -g -Wall main.c
gcc -c -g -Wall logoff.c
gcc -o main -g -Wall main.o logoff.o
ld: duplicate symbol _logoff in logoff.o and main.o
我在 logoff.c 中有一个名为 logoff 的函数,但我在 main.c 中搜索了文本“logoff”,但什么也没找到(该函数甚至还没有被调用!)。
如果我将函数的名称更改为 log_off ,它就可以工作。 文件中还有第二个函数,除非它的名称也更改,否则它会导致相同的错误。
有什么原因可能会发生这种情况吗? 我在两个不同的系统上遇到这个问题。 可能相关的一件事是我在另一个项目中使用了相同的 logoff.c 文件,但它没有连接到这个项目。
I have a project consisting of two files, main.c and logoff.c. When I try to compile them I get this error:
gcc -c -g -Wall main.c
gcc -c -g -Wall logoff.c
gcc -o main -g -Wall main.o logoff.o
ld: duplicate symbol _logoff in logoff.o and main.o
I have a function named logoff in logoff.c, but I have searched main.c for the text "logoff" and have found nothing (the function is not even called yet!).
If I change the name of the function to log_off it works. There is a second function in the file which then causes the same error unless its name is changed as well.
Is there any reason why this might occur? I have this problem on two different systems. One thing that might be relevant is that I used the same logoff.c file in another project but it is not connected to this one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建一个仅包含注销函数声明的 logoff.h 文件,例如
void logoff(void);
然后,在 main.c 中将其包含在
#include "logoff.h"
。 不要包含 logoff.c,因为编译器将编译该函数两次,然后链接器将看到两个同名的函数。如果将其更改为 log_off,然后仅重新编译其中之一,它似乎可以工作。 另一个目标文件仍将编译旧的注销函数。因此链接器会看到一个 log_off 和一个 logoff。 这就是这个名字似乎对你有用的原因。
Create a logoff.h file with only the function declaration of logoff, like
void logoff(void);
Then, in main.c include it with
#include "logoff.h"
. Don't include logoff.c, as the compiler will compile the function two times, and the linker will see two functions of that name then.It appears to work if you change it to log_off, and then only recompile one of them. The other object-file will still have the old logoff function compiled in. Thus the linker sees one log_off and one logoff. That's the reason it appeared to work for you with that name.
你在 main.c 中 #include 或 #import logoff.c 吗?
你做到了——好吧,这就是你的问题。 logoff.c 包含在 main.c 中,因此 main 定义了 _logoff 和 _main。 现在您还编译 logoff.c,它定义了 _logoff。 然后尝试链接两者,这意味着生成的二进制文件包含符号 _main、_logoff 和 _logoff,这正是链接器告诉您的内容。
Do you #include or #import logoff.c in main.c?
You did - well there's your problem. logoff.c is being included in main.c, so main defines _logoff and _main. Now you also compile logoff.c, which defines _logoff. Then you try and link the two, which means the resulting binary includes the symbols _main, _logoff and _logoff, which is exactly what the linker is telling you about.