c++ - 链接器未在目标文件中找到现有引用

标签 c++ linker g++

我在编译项目时遇到问题,基本上是链接对象。链接器提示:

$ g++ -o bin/program obj/linux64/Debug/src/main.o  [... more object files ...] ../../../addons/obj/linux64/Debug/ofxLua/libs/lua/lua/lapi.o [...many other object files and libraries...]
../../../addons/obj/linux64/Debug/ofxLua/libs/luabind/src/scope.o: In function `~lua_pop_stack':
../../../addons/ofxLua/libs/luabind/src/scope.cpp:122: undefined reference to `lua_settop(lua_State*, int)'
[...many more undefined reference errors...]

但是如果我检查目标文件,我会发现符号:

$ nm ../../../addons/obj/linux64/Debug/ofxLua/libs/lua/lua/lapi.o | grep lua_settop
000000000000045c T lua_settop

我检查了 g++ 参数 are correctly ordered .

造成这种行为的原因是什么?我能想到的唯一解释是,不同源文件中使用的 header 以某种方式被以前的包含或定义以某种方式改变。有什么方法可以检查生成的完整符号,以便我可以确定情况是这样吗?

最佳答案

如果要包含用 C 编写的代码的 header ,则需要将 #include 语句括在 extern "C"{ ... } 中,以便C++ 编译器知道对这些符号使用 C 链接,而不是 C++ 链接(它使用名称修饰来允许方法重载)。

例如:

extern "C" {
#include <file.h>
}

实际上头文件本身应该这样做,以避免您需要这样做,并且我认为不这样做是一个错误:

//
// file.h
//
#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}    // extern "C"
#endif

关于c++ - 链接器未在目标文件中找到现有引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467242/

相关文章:

C++ 可变大小对象可能未初始化

C++类静态变量问题 - C programmer new to C++

c++ - 无论签名如何,函数指针都有效?惊喜

python - 传递 Python 元组代替 C++ 结构函数参数是否对性能有影响?

visual-studio - Visual Studio Link.exe 错误 : "extra operand"

无法使用 ALSA 编译

C++ STL 容器中的 NULL 指针

c++ - 无法链接CMake中的本地库

c++ - 重新排序 gnu autotools 链接器标志

c++ - operator= 的模糊重载使用 move 分配和按值复制分配传递