首页 > 解决方案 > 在 Cygwin 上链接 Boost 库

问题描述

我已经在这里待了几个小时,所以我来这里寻求帮助。很确定我几乎已经弄清楚了,但我仍然有未定义引用的链接器错误boost::system::generic_categoryand boost::system::system_category

我只有一个文件要链接以生成可执行文件。

我开始编译它以制作一个目标文件:

g++ -c main.cpp -I C:/boost/boost_1_61_0

这成功地创建了 main.o。

我的下一个也是最后一个目标是将它链接到一个可执行文件。我尝试了与我在其他帖子上读到的不同的东西:

g++ main.o -L C:/boost/boost_1_61_0/stage/lib

g++ main.o -L C:/boost/boost_1_61_0/stage/lib/libboost_system.a

g++ main.o -lboost_system

结果要么告诉我它找不到库或类似的东西:

main.o:main.cpp:(.text+0x89): undefined reference to `boost::system::generic_category()'
main.o:main.cpp:(.text+0x89): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::system::generic_category()'
main.o:main.cpp:(.text+0x95): undefined reference to `boost::system::generic_category()'
main.o:main.cpp:(.text+0x95): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::system::generic_category()'
main.o:main.cpp:(.text+0xa1): undefined reference to `boost::system::system_category()'
main.o:main.cpp:(.text+0xa1): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::system::system_category()'
main.o:main.cpp:(.text$_ZN5boost11this_thread9sleep_forERKNS_6chrono8durationIlNS_5ratioILl1ELl1000000000EEEEE[_ZN5boost11this_thread9sleep_forERKNS_6chrono8durationIlNS_5ratioILl1ELl1000000000EEEEE]+0x24): undefined reference to `boost::this_thread::hiden::sleep_for(timespec const&)'
main.o:main.cpp:(.text$_ZN5boost11this_thread9sleep_forERKNS_6chrono8durationIlNS_5ratioILl1ELl1000000000EEEEE[_ZN5boost11this_thread9sleep_forERKNS_6chrono8durationIlNS_5ratioILl1ELl1000000000EEEEE]+0x24): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `boost::this_thread::hiden::sleep_for(timespec const&)'
collect2: error: ld returned 1 exit status

我知道我正确构建了 boost 库,因为在 stage/lib 目录中的许多其他库中都有一个 libboost_system.a 文件。请问有什么想法吗?

标签: c++boostg++cygwin

解决方案


让我们从查看您尝试过的命令开始。

g++ main.o -L C:/boost/boost_1_61_0/stage/lib

这告诉g++C:/boost/boost_1_61_0/stage/lib目录中查找库。它没有说明要引入哪些库,但是一旦您这样做,g++就会在那里查看。

由于您的代码引用了boost::system::generic_category在中找到的东西(如 ),boost_system并且由于您没有告诉链接器拉入该库,因此这些引用最终是未定义的。

g++ main.o -L C:/boost/boost_1_61_0/stage/lib/libboost_system.a

这告诉g++C:/boost/boost_1_61_0/stage/lib/libboost_system.a目录中查找库。-L由于这(可能)不是目录,因此该标志没有实际效果。

g++ main.o -lboost_system

这告诉g++boost_system库中链接。虽然链接器知道如何将库名(例如boost_system)转换为相应的文件名(例如libboost_system.a),但没有指示可以在哪里找到该文件。所以链接器将在它知道的默认目录中查找。当在那里找不到文件时,g++抱怨找不到库。


此时您应该看到需要组合的两部分:告诉链接器要拉入哪个库以及在哪里找到它。

g++ main.o -lboost_system -L C:/boost/boost_1_61_0/stage/lib

推荐阅读