在 Cygwin 上链接 Boost 库

Linking Boost library on Cygwin

我已经在这里待了几个小时了,所以我来这里寻求帮助。 可以肯定的是,我几乎已经弄清楚了,但我仍然有 linker 未定义引用 boost::system::generic_categoryboost::system::system_category 的错误。

我只有一个文件,我正在尝试 link 生成可执行文件。

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

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

这成功创建了 main.o。

我的下一个也是最后一个 objective 是 link 将其转换为可执行文件。我尝试了与我在其他帖子上看到的不同的东西:

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 文件以及许多其他库。有什么想法吗?

让我们先看看您尝试过的命令。

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

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

由于您的代码引用了在 boost_system 中找到的内容(例如 boost::system::generic_category),并且由于您没有告诉 link 人员拉入该库,因此这些引用最终未定义。

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 库中的 link。虽然 linker 知道如何将库名(例如 boost_system)转换为相应的文件名(例如 libboost_system.a),但没有指明可以在何处找到该文件。所以 linker 将在它知道的默认目录中查找。当在那里找不到文件时,g++ 抱怨找不到库。


此时您应该看到需要合并的两个部分:告诉 linker 要引入哪个库以及在哪里找到它。

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