如何在CMakeLists.txt中添加boost库
我需要添加boost库到我的CMakeLists.txt。 你怎么做,或者如何添加它?
把它放在你的CMakeLists.txt文件中(如果你愿意,可以把任何选项从OFF改为ON): 
 set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost 1.45.0 COMPONENTS *boost libraries here*) if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIRS}) add_executable(progname file1.cxx file2.cxx) target_link_libraries(progname ${Boost_LIBRARIES}) endif() 
 很明显,你需要把你想要的库放在*boost libraries here*放在*boost libraries here* 。 例如,如果你使用filesystem和regex库,你会写: 
 find_package(Boost 1.45.0 COMPONENTS filesystem regex) 
您可以使用find_package来search可用的boost库。 它推迟searchBoost FindBoost.cmake ,这是与CMake默认安装。
 findBoost后, find_package()调用将会填充许多variables(检查FindBoost.cmake的引用)。 其中包括BOOST_INCLUDE_DIRS ,Boost_LIBRARIES和Boost_XXX_LIBRARY variabels,其中XXX由特定的Boost库取代。 您可以使用这些来指定include_directories和target_link_libraries 。 
例如,假设你需要boost :: program_options和boost :: regex,你可以这样做:
 find_package( Boost REQUIRED COMPONENTS program_options regex ) include_directories( ${Boost_INCLUDE_DIRS} ) add_executable( run main.cpp ) # Example application based on main.cpp # Alternatively you could use ${Boost_LIBRARIES} here. target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} ) 
一些一般的提示:
- 在search时,FindBoost检查环境variables$ ENV {BOOST_ROOT}。 如果需要,可以在调用find_package之前设置这个variables。
-  当你有多个版本的boost(multithreading,静态,共享等)时,你可以在调用find_package之前指定你想要的configuration。 通过将以下某些variables设置为On来执行此操作:Boost_USE_STATIC_LIBS,Boost_USE_MULTITHREADED,Boost_USE_STATIC_RUNTIME
-  在Windows上searchBoost时,请注意自动链接。 阅读参考资料中的“关于Visual Studio用户的注意事项”。
-  我的build议是禁用自动链接并使用cmake的依赖性处理: add_definitions( -DBOOST_ALL_NO_LIB )
-  在某些情况下,您可能需要明确指定使用dynamicBoost: add_definitions( -DBOOST_ALL_DYN_LINK )
 
-  我的build议是禁用自动链接并使用cmake的依赖性处理: 
将@ LainIwakura的现代CMake语法与导入目标匹配,这将是:
 set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost 1.45.0 COMPONENTS filesystem regex) if(Boost_FOUND) add_executable(progname file1.cxx file2.cxx) target_link_libraries(progname Boost::filesystem Boost::regex) endif() 
 请注意,由于已经通过导入的目标Boost::filesystem和Boost::regex来处理,因此不再需要手动指定include目录。 
  regex和filesystem可以被你需要的任何boost库replace。 
我同意答案1和2 。 不过,我更喜欢分别指定每个库。 这使得大项目中的依赖更加清晰。 但是,(区分大小写的)variables名称有被误认的危险。 在这种情况下,没有直接的cmake错误,但稍后会有一些未定义的引用链接器问题,这可能需要一些时间才能解决。 因此我使用下面的cmake函数:
 function(VerifyVarDefined) foreach(lib ${ARGV}) if(DEFINED ${lib}) else(DEFINED ${lib}) message(SEND_ERROR "Variable ${lib} is not defined") endif(DEFINED ${lib}) endforeach() endfunction(VerifyVarDefined) 
对于上面提到的例子,这看起来像:
 VerifyVarDefined(Boost_PROGRAM_OPTIONS_LIBRARY Boost_REGEX_LIBRARY) target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} ) 
如果我写了“BOOST_PROGRAM_OPTIONS_LIBRARY”,那么cmake会触发一个错误,并且不会被链接器触发。