首页 > 解决方案 > 使用带有clang而不是gcc的boost::filesystem链接的程序

问题描述

我有一个非常简单的程序 using 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

为什么当 Clang 没有时 GCC 会产生链接时错误?boost::system即使提供了参数,我该如何诊断为什么链接器无法在 GCC 路径中找到符号?

标签: c++linkerboost-filesystem

解决方案


您应该假设“一次性链接”,这意味着较低级别boost_system必须出现在较高级别之后boost_filesystem


推荐阅读