首页 > 解决方案 > Cmake 不能包含来自 main 的 boost 库

问题描述

我在 Windows 上使用带有 Visual Studio 2019 的 boost-beast。在我将现有类添加到 main.cpp 之前,一切正常。然后其中一个 .h 文件无法打开 boost 文件。我将#include 语句移到 .cpp 文件中。它仍然失败并出现相同的错误。

最简单的代码是:

#include <algorithm>
#include <iostream>
#include <boost/system/error_code.hpp>
#include "pml_webserver/pml_webserver.h"
#include "pml_webserver/product_factory.h"
#include "pml_webserver/config.h"

int main(int argc, char* argv[])
{
    // omitted
}

编译所有其他文件。Main.cpp 导致此错误:

[4/12] Building CXX object CMakeFiles\pml_webserver.dir\src\main.cpp.obj

FAILED: CMakeFiles/pml_webserver.dir/src/main.cpp.obj 
  C:\PROGRA~2\MICROS~2\2019\PROFES~1\VC\Tools\MSVC\1421~1.277\bin\HostX64\x64\cl.exe  /nologo /TP  -IC:\Users\me\source\xplatform\core_pml_webserver\include -Iinclude /DWIN32 /D_WINDOWS /W3 /GR /EHsc /MDd /ZI /Ob0 /Od /RTC1 /JMC   -std:c++17 /showIncludes /FoCMakeFiles\pml_webserver.dir\src\main.cpp.obj /FdCMakeFiles\pml_webserver.dir\ /FS -c C:\Users\me\source\xplatform\core_pml_webserver\src\main.cpp

C:\Users\me\source\xplatform\core_pml_webserver\include\pml_webserver\base_ws_handler.h(10): fatal error C1083: Cannot open include file: 'boost/system/error_code.hpp': No such file or directory

我无法确定问题出在我没有多少经验的 Cmake 上,还是由命名空间引起的。

编辑:部分 CMakeLists.txt

cmake_minimum_required(VERSION 3.12)
project(pml_webserver CXX)

find_package(Boost 1.70.0 REQUIRED COMPONENTS system date_time)
configure_file(include/pml_webserver/config.h.in
    ${CMAKE_BINARY_DIR}/include/pml_webserver/config.h
)

add_library(pml_webserver_lib
    src/webserver.cpp
    src/base_ws_handler.cpp
    src/ws_handler_factory.cpp
    src/product_ws_handler.cpp
    src/product_factory.cpp

set_target_properties(pml_webserver_lib PROPERTIES PREFIX "")

target_include_directories(pml_webserver_lib PUBLIC ${CMAKE_SOURCE_DIR}/include PUBLIC ${CMAKE_BINARY_DIR}/include)
target_link_libraries(pml_webserver_lib
 PRIVATE Boost::system
 PRIVATE Boost::date_time
 )

add_executable(pml_webserver src/main.cpp)
target_link_libraries(pml_webserver pml_webserver_lib)

我不知道在哪里CMAKE_SOURCE_DIR定义CMAKE_BINARY_DIR

标签: c++visual-studiocmakeboost-asio

解决方案


As @drescherjm commented, your issue is that the include path for boost is not properly setup,

If you are using cmake, then your CMakeLists.txt file should contain something like:

find_package(Boost REQUIRED COMPONENTS system)
if(Boost_FOUND)
  target_include_directories(${PROJECT_NAME} PRIVATE ${Boost_INCLUDE_DIRS})
  target_link_libraries(${PROJECT_NAME} PRIVATE Boost::system)
endif(Boost_FOUND)

Note: you should also set the environment variables: BOOST_ROOT and BOOST_LIBRARYDIR to the locations of the boost root and library directories respectively, so that cmake can find boost.

If you aren't comfortable using cmake then you can add the the locations of the boost root and library binary directories directly to Visual Studio as described here.


推荐阅读