如何使用CMake链接C ++程序和Boost

我的cmake文件应该看起来像在Ubuntu下连接我的程序与boost库吗?

运行make时显示错误:

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

主文件非常简单:

 #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; } 

我设法做到这一点,我已经添加到我的cmake文件的唯一线路是:

 target_link_libraries( my_target_file ${Boost_PROGRAM_OPTIONS_LIBRARY} ) 

在CMake中,您可以使用find_package来查找您需要的库。 通常有一个FindBoost.cmake与您的CMake安装。

据我记得,它将被安装到/usr/share/cmake/Modules/以及其他通用库的查找脚本。 你可以检查该文件中的文档以获取更多关于它是如何工作的信息。

我现在不在工作,所以我只能提供一个例子:

 FIND_PACKAGE( Boost 1.40 COMPONENTS program_options REQUIRED ) INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} ) ADD_EXECUTABLE( anyExecutable myMain.cpp ) TARGET_LINK_LIBRARIES( anyExecutable LINK_PUBLIC ${Boost_LIBRARIES} ) 

希望这个代码有帮助。

  • 这里是关于FindBoost.cmake的官方文档 。
  • 而实际的FindBoost.cmake (托pipe在Github上)

以下是我的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} ) 

哪个Boost库? 其中许多是纯模板,不需要链接。

编辑现在,实际上显示了具体的例子,告诉我们你想要Boost程序选项(甚至更多的告诉我们你在Ubuntu上),你需要做两件事情:

  1. 安装libboost-program-options-dev以便你可以链接它
  2. 告诉cmake链接到libboost_program_options

我主要使用Makefiles,所以这里是直接的命令行使用:

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

看起来不是很多。

对于CMake,您需要将boost_program_options添加到库列表中,IIRC将通过CMakeLists.txt SET(liblist boost_program_options)来完成。

为现代CMake语法调整@MOnsDaR答案,以便导入目标,这将是:

 find_package(Boost 1.40 COMPONENTS program_options REQUIRED) add_executable(anyExecutable myMain.cpp) target_link_libraries(anyExecutable Boost::program_options) 

请注意,没有必要手动指定include目录,因为已经通过导入的目标Boost::program_options