我有一个使用boost::filesystem
的非常简单的程序,它取自库的教程。
// fs_example.cpp
#include <boost/filesystem.hpp>
#include <iostream>
using namespace boost::filesystem;
int main() {
path p = current_path();
directory_iterator it{p};
while (it != directory_iterator()) {
std::cout << *it++ << 'n';
}
}
我用以下非常简单的脚本构建它,它应该以正确的顺序向链接器提供正确的参数:
#!/bin/sh
set -u
${CXX}
-Wall
-Werror
--std=c++14
-lboost_system
-lboost_filesystem
-o fs_example
fs_example.cpp
使用env CXX=clang++ ./build.sh
,程序编译并链接
$ env CXX=clang++ ./build.sh
$ ls
build.sh* fs_example* fs_example.cpp
使用env CXX=g++ ./build.sh
,程序编译失败。
$ env CXX=g++ ./build.sh
/tmp/ccFcZ3W6.o: In function `__static_initialization_and_destruction_0(int, int)':
fs_example.cpp:(.text+0x1c1): undefined reference to `boost::system::generic_category()'
...
collect2: error: ld returned 1 exit status
为什么GCC会产生链接时间错误,而Clang没有?我该如何诊断为什么即使提供了参数,链接器也无法在GCC路径中的boost::system
中找到符号?
您应该假设"一次链接",这意味着较低级别的boost_system
必须出现在较高级别的boost_filesystem
之后。