You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自行编译Boost后编译C++程序出现undefined reference错误

问题:自行编译Boost 1.80.0后编译C++程序出现undefined reference链接错误

编译Boost的操作步骤

我在~/libs/目录下编译Boost 1.80.0的命令如下:

tar -xvzf boost_1_80_0.tar.gz
cd boost_1_80_0/
./bootstrap.sh --prefix=. 
./b2 -std=C++11
./b2  headers
./b2 install

编译完成后,生成了boost_1_80_0/stage/lib/libboost_filesystem.a文件。

测试用C++代码

#include <boost/filesystem.hpp>
#include <iostream>

int main()
{
    boost::filesystem::path directory = ".";
    boost::filesystem::directory_iterator end_itr;
    for( boost::filesystem::directory_iterator itr(directory); itr!=end_itr;++itr  )
    {
        boost::filesystem::path pathname=itr->path();
        std::cout<< pathname << std::endl;
    }
}

编译命令及错误信息

我使用以下命令编译程序:

LC_ALL=C  c++ -std=c++11 -I ~/libs/boost_1_80_0/stage/lib  ~/libs/boost_1_80_0/stage/lib/libboost_filesystem.a  ecm.cpp -o ecm

执行后出现一系列未定义引用的链接错误:

/usr/bin/ld: /tmp/ccXuD16q.o: in function `boost::filesystem::detail::dir_itr_imp::~dir_itr_imp()':
ecm.cpp:(.text._ZN5boost10filesystem6detail11dir_itr_impD2Ev[_ZN5boost10filesystem6detail11dir_itr_impD5Ev]+0x27): undefined reference to `boost::filesystem::detail::dir_itr_close(void*&, void*&)'
/usr/bin/ld: /tmp/ccXuD16q.o: in function `boost::filesystem::directory_iterator::directory_iterator(boost::filesystem::path const&, boost::filesystem::directory_options)':
ecm.cpp:(.text._ZN5boost10filesystem18directory_iteratorC2ERKNS0_4pathENS0_17directory_optionsE[_ZN5boost10filesystem18directory_iteratorC5ERKNS0_4pathENS0_17directory_optionsE]+0x38): undefined reference to `boost::filesystem::detail::directory_iterator_construct(boost::filesystem::directory_iterator&, boost::filesystem::path const&, unsigned int, boost::system::error_code*)'
/usr/bin/ld: /tmp/ccXuD16q.o: in function `boost::filesystem::directory_iterator::increment()':
ecm.cpp:(.text._ZN5boost10filesystem18directory_iterator9incrementEv[_ZN5boost10filesystem18directory_iterator9incrementEv]+0x1d): undefined reference to `boost::filesystem::detail::directory_iterator_increment(boost::filesystem::directory_iterator&, boost::system::error_code*)'
collect2: error: ld returned 1 exit status

我是不是遗漏了头文件?

说明:此问题与其他类似问题的区别在于,自行编译Boost时需要指定具体的包含目录。

解决方案

问题源于两个错误:

  • 编译参数顺序错误:链接库文件必须放在源文件之后,否则链接器无法正确匹配源文件中引用的符号
  • 头文件搜索目录指定错误:-I参数需要指向Boost的根目录(即包含boost/子文件夹的路径),而不是库文件所在的stage/lib目录

正确的编译命令应为:

c++ -std=c++11 ecm.cpp -o ecm  -I ~/libs/boost_1_80_0/  ~/libs/boost_1_80_0/stage/lib/libboost_filesystem.a

内容的提问来源于stack exchange,提问作者Laurent Claessens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 22:40:50