Search code examples
c++boost

Linking to a Boost library


I'm new to the Boost library usage, and I cannot figure out why the following is not working.

I want to compile the following code from the library's documentation:

#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;
    }
}

As laid out on the documentation, we can use two methods to compile.

Method 1: (ok)

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

Method 2: (not ok)

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

Using Method 1, everything is fine. However, using Method 2, when I run the executable I have:

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

What am I missing here?

Thanks in advance.


Solution

  • Presumably /usr/local/lib/ contains both a static library (libboost_regex.a) and a shared library (libboost_regex.so), if you just specify -lboost_regex on your linker command line gcc by default prefers the shared library over the static one. The only way to prevent this is to pass the -static flag but this then stops gcc from linking to any shared libraries which may not be what you want. You can also remove the shared libraries from the directory so that gcc can only use the static ones.

    To fix the problem at runtime make sure that /usr/local/lib is listed in /etc/ld.so.conf then run sudo ldconfig to update the ldconfig cache so that the dynamic linker knows where to look for the boost shared libraries at runtime.