在 Visual Studio 上使用 CMakeLists 提升

Boost with CMakeLists on Visual Studio

我正在尝试 运行 一些带有 boost 的代码,但我无法包含任何 boost 文件,例如“boost/timer/timer.hpp”。我的 CMakeLists 包含

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

我的 cpp 文件包含

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

using namespace std;

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

当我尝试构建它时,出现错误:“无法打开包含文件 'boost/timer/timer.hpp'”

您在这里使用了错误的不存在的变量。要将包含 Boost 目录设置到您的项目,您需要使用 Boost_INCLUDE_DIRS,变量的大小写很重要。并且您的 link 目录应设置为 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}")

您的小项目可以通过使用导入的目标 Boost::headers 进一步简化,如下所示:

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}")