【问题标题】:Undefined reference, but objdump shows the function is in the object file?未定义的引用,但 objdump 显示函数在目标文件中?
【发布时间】:2015-11-13 03:22:43
【问题描述】:

基本上,我使用g++ -c -o one.o one.c 分别编译几个C 文件,然后尝试将它们与g++ -o one.exe one.o two.o three.o 链接。链接器抱怨对 one.c 调用并在 two.c 中声明的函数的未定义引用。但是如果我这样做objdump -d two.o,函数就在那里,所以我很困惑为什么链接器找不到它们?

e:如果我给链接器选项-y <symbol>,它会打印定义符号的目标文件。

【问题讨论】:

  • 是 C 还是 C++。另外,显示一些示例代码。也许您的函数声明与您对函数的定义不同。
  • C 和 C++ 的混合,这有关系吗?我会尝试发布一些代码,但声明肯定与定义匹配。
  • 是的,实际上。例如,name mangling 中的 C 和 C++ 之间的差异可能会给您带来这种痛苦。所以,是的,有点重要。
  • Ughhhhh 就是 @user4581301 - 必须在子目录的 Makefile 中将 gcc 更改为 g++。就是这样。将在几秒钟内发布带有小示例的答案。
  • 很高兴这是一个快速的。

标签: c++ c linker


【解决方案1】:

设置重现:

一个.cpp:

#include "two/two.h"
int main(void) {
    two();
    return 0;
}

生成文件:

all: one

one: one.o two.o
    g++ -o one.exe one.o two/two.o

one.o:
    g++ -c -o one.o one.cpp

two.o:
    $(MAKE) -C two

两个/两个.h:

void two(void);

两个/两个.c:

#include <stdio.h>
#include "two.h"
void two(void) { printf("Two\n"); }

两个/Makefile:

all:
    gcc -c -o two.o two.c

我所做的只是将两个/Makefile 更改为使用 g++ 而不是 gcc:

两个/Makefile:

all:
    g++ -c -o two.o two.c

【讨论】:

  • 您可以使用变量 $(CC) 和 $(CXX) 来避免麻烦。如果您混合使用语言,还请阅读“extern "C"”
【解决方案2】:

我也发生了完全相同的事情。 在头文件(.h)中做

#ifdef __cplusplus
extern "C" {
#endif

// Your code

#ifdef __cplusplus
}
#endif

解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多