Search code examples
c++windowsvisual-studioboostcmake

Boost with CMakeLists on Visual Studio


I'm trying to run some code with boost, but i can't include any boost file, like "boost/timer/timer.hpp". My CMakeLists contains

cmake_minimum_required(VERSION 3.10)
project(Converter)

find_package(Boost)
include_directories(${BOOST_INCLUDE_DIRS})
LINK_DIRECTORIES(${Boost_LIBRARIES})
add_executable(Converter converter.cpp)

TARGET_LINK_LIBRARIES(Converter  ${Boost_LIBRARIES})
message("boost lib: ${Boost_LIBRARY_DIRS}, inc: ${Boost_INCLUDE_DIR}")

CMake answer

My cpp file contains

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

using namespace std;

int main() {
    cout << "Hello world!" << endl;
    return 0;
}

And when i am trying to build it, there is a error: "Cannot open include file 'boost/timer/timer.hpp'"


Solution

  • You are using a wrong non existing variable here. To set the include Boost directories to your project you need to use Boost_INCLUDE_DIRS, the case of the variable matters. And your link directories should be set to Boost_LIBRARY_DIRS.

    cmake_minimum_required(VERSION 3.10)
    project(Converter)
    
    find_package(Boost COMPONENTS timer)
    include_directories(${Boost_INCLUDE_DIRS})
    link_directories(${Boost_LIBRARY_DIRS})
    add_executable(Converter converter.cpp)
    
    target_link_libraries(Converter PUBLIC ${Boost_LIBRARIES})
    message("boost lib: ${Boost_LIBRARY_DIRS}, inc: ${Boost_INCLUDE_DIR}")
    

    Your small project can be further simplified by using the imported targets Boost::headers as follows:

    cmake_minimum_required(VERSION 3.10)
    project(Converter)
    
    find_package(Boost COMPONENTS timer REQUIRED)
    add_executable(Converter converter.cpp)
    
    target_link_libraries(Converter PUBLIC Boost::headers Boost::timer)
    message("boost lib: ${Boost_LIBRARY_DIRS}, inc: ${Boost_INCLUDE_DIRS}")