Link library boost with cmake?

Asked

Viewed 200 times

2

I’m trying to use the c++ boost library. Reading a tutorial on their website, I came across this and do not know how to do. It’s said I have to include #include <boost/test/unit_test.hpp> and link to this lib : libunit_test_framework.lib. I don’t want to use the prepackaged, which is the option they give the lowest, you want to be able to do it the first way. How do I link with that lib?

Source: Boost Test Library Tutorial

Tutorial

1 answer

0

You can use the module Findboost, which comes in the standard Cmake installation to include boost in your project. The syntax is as follows::

find_package(Boost
  [version] [EXACT]      # Versão mínima ou exata (EXACT).
  [REQUIRED]             # Emita um erro se Boost não for encontrado.
  [COMPONENTS <libs>...] # Use bibliotecas específicas do Boost.
  )

For example, to use Boost in the exact version 1.65.1, package required for build to be successful, with libraries Filesystem, Regex and Algorithm:

find_package(Boost 1.65.1 EXACT REQUIRED COMPONENTS filesystem regex)

If the boost package is found and its version matches the one specified, then the library will be available for use in the rest of your Cmakelists.txt, via namespace Boost::.

The attentive reader will notice that there is no mention of the library Algorithm above. How this library has the characteristic of being header-only (implemented all in a header), there is no component to be required, because there is nothing to build and link. Including the header is enough. You can link the target Boost::boost the target of your application and include directories will be added automatically.

For example, the following CMakeLists.txt:

cmake_minimum_required(VERSION 3.9)
project(ProjetoExemplo)
include(FindBoost)
find_package(Boost 1.65.1 EXACT REQUIRED COMPONENTS filesystem regex)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE Boost::boost Boost::filesystem Boost::regex)

Compiling the simple example below as main.cpp:

#include "boost/algorithm/cxx11/none_of.hpp"
#include "boost/filesystem.hpp"
#include "boost/regex.hpp"

int main() {}

Executing the following commands:

cmake .
cmake --build .

Should generate an executable called app. Note that boost header inclusions are made using "..." and not <...>. This is because the include directories are passed pro compiler by Cmake, so it is better to use them that way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.