【问题标题】:Linking errors on library built using cmake使用 cmake 构建的库上的链接错误
【发布时间】:2013-03-14 21:41:12
【问题描述】:

我想我只是犯了一个简单的错误,但我没有得到哪个.. 无论如何,我正在开发一个库,我也在使用 cmake 为项目构建 Makefile:https://github.com/immapoint/NaNO3/blob/master/CMakeLists.txt

编译库时一切正常;它构建以下文件:

bin/libNaNO3.dll
lib/libNaNO3.dll.a (I don't like that name as well)

为了测试整个事情,我建立了另一个项目,也使用 cmake。 https://github.com/immapoint/NaNO3TestApp/blob/master/CMakeLists.txt

测试库的主文件如下所示: https://github.com/immapoint/NaNO3TestApp/blob/master/src/main.cpp

但是在编译主文件时,我遇到了以下错误:

CMakeFiles/NaNO3TestApp.dir/objects.a(main.cpp.obj):main.cpp:(.text+0xbf): undefined reference to `nano::Event<int>::attach(std::function<void(int)> *)`
CMakeFiles/NaNO3TestApp.dir/objects.a(main.cpp.obj):main.cpp:(.text+0xd3): undefined reference to `nano::Event<int>::notify(int)`
[...]ld.exe: CMakeFiles/NaNO3TestApp.dir/objects.a(main.cpp.obj): bad reloc address 0x8 in section `.rdata'

无论我是使用 make/cmake 构建项目还是直接使用编译源文件都会出现此错误

g++ -Wall -pedantic -ansi -std=c++0x main.cpp [-L./lib -I./include] -lNaNO3 

所以问题似乎不在于 cmake 而在于 ld。 我正在使用 CMake 2.8 版和包含 GCC 4.7.2 版的 MinGW。

其他信息:

使用 -fPIC 的编译器输出:

【问题讨论】:

  • 您可以将 -fPIC 开关添加到您的构建中吗?

标签: c++ c++11 cmake ld


【解决方案1】:

这与 CMake 或链接器无关。您需要在头文件中包含nano::Event 成员函数的定义,而不是在单独的源文件中,因为模板是在编译时实例化的。当链接器到达那里时,为时已晚。

如需更全面的解释,请参阅Why should the implementation and the declaration of a template class be in the same header file?http://www.parashift.com/c++-faq-lite/templates-defn-vs-decl.html

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多