首页 > 解决方案 > 链接到 Boost 库

问题描述

我是 Boost 库使用的新手,我无法弄清楚为什么以下内容不起作用。

我想从库的文档中编译以下代码:

#include <boost/regex.hpp>
#include <iostream>
#include <string>

int main() {
    std::string line;
    boost::regex pat( "^Subject: (Re: |Aw: )*(.*)" );

    while (std::cin) {
        std::getline(std::cin, line);
        boost::smatch matches;
        if (boost::regex_match(line, matches, pat))
            std::cout << matches[2] << std::endl;
    }
}

如文档所述,我们可以使用两种方法进行编译。

方法一:(好的)

g++ -I /usr/local/include/boost/main.cpp -o main /usr/local/lib/libboost_regex.a

方法二:(不行)

g++ -I /usr/local/include/boost/main.cpp -o main -L/usr/local/lib/ -lboost_regex

使用方法1,一切都很好。但是,使用方法 2,当我运行可执行文件时,我有:

./main: error while loading shared libraries: libboost_regex.so.1.75.0: cannot open shared object file: No such file or directory

我在这里想念什么?

提前致谢。

标签: c++boost

解决方案


大概/usr/local/lib/包含一个静态库(libboost_regex.a)和一个共享库(libboost_regex.so),如果您只是-lboost_regex在链接器命令行上指定 gcc 默认情况下更喜欢共享库而不是静态库。防止这种情况的唯一方法是传递-static标志,但这会阻止 gcc 链接到任何可能不是您想要的共享库。您还可以从目录中删除共享库,以便 gcc 只能使用静态库。

要在运行时解决问题,请确保在运行时列出该问题以/usr/local/lib更新缓存,以便动态链接器知道在运行时在哪里查找 boost 共享库。/etc/ld.so.confsudo ldconfigldconfig


推荐阅读