How to link C++ program with Boost using CMake


Answers

The following is my configuration:

cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )
Question

What should my cmake file should look like for linking my program with boost library under Ubuntu?

The errors show during running make:

main.cpp:(.text+0x3b): undefined reference to `boost::program_options::options_description::m_default_line_length'

The main file is really simple:

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/option.hpp>
using namespace std;
#include <iostream>

namespace po = boost::program_options;

int main(int argc, char** argv) {

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ;

    return 0;
}

I've managed to do that, the only lines that I've added to my cmake files were:

target_link_libraries(
my_target_file
${Boost_PROGRAM_OPTIONS_LIBRARY}
)



Which Boost library? Many of them are pure templates and do not require linking.

Edit Now that actually showed concrete example which tells us that you want Boost program options (and even more told us that you are on Ubuntu), you need to do two things:

  1. install libboost-program-options-dev so that you can link against it
  2. tell cmake to link against libboost_program_options

I mostly use Makefiles so here is the direct command-line use:

$ g++ boost_program_options_ex1.cpp -o bpo_ex1 -lboost_program_options
$ ./bpo_ex1
$ ./bpo_ex1 -h
$ ./bpo_ex1 --help
$ ./bpo_ex1 -help
$ 

Doesn't do a lot it seems.

For CMake, you need to add boost_program_options to the list of libraries, IIRC this is done via SET(liblist boost_program_options) in your CMakeLists.txt.




Links