一 内容
-
请先阅读 CMake Tutorial2_2 设置使用库的开关 。
-
主要说明 如何增加库的使用要求。
-
“使用要求”简述
Usage requirements allow for far better control over a library or executable’s link and include line while also giving more control over the transitive property of targets inside CMake.
The primary commands that leverage usage requirements are:
-
使用要求允许更好地控制库或可执行文件的链接和包含行,同时还可以更好地控制 CMake 内目标的传递属性。
利用使用要求的主要命令是:target_compile_definitions(<target> <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...]) target_compile_options(<target> [BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...]) target_include_directories(<target> [SYSTEM] [AFTER|BEFORE] <INTERFACE|PUBLIC|PRIVATE> [items1...] [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...]) target_link_libraries(<target> <PRIVATE|PUBLIC|INTERFACE> <item>... [<PRIVATE|PUBLIC|INTERFACE> <item>...]...)
-
下面以target_link_libraries举例说明。
-
文件目录
step3 |- MathFunctions |- CMakeLists.txt |- MathFunctions.h |- mysqrt.cc |- CMakeaLists.txt |- main.cc |- TutorialConfig.h.in
-
修改MathFunctions/CMakeLists.txt
add_library(MathFunctions mysqrt.cc) # --add # state that anybody linking to MathFunctions needs to include the current source directory, # while MathFunctions itself doesn't # 即链接方不需处理包含MathFunctions源文件目录 target_include_directories(MathFunctions INTERFACE ${CMAKE_CURRENT_SOURCE_DIR} )
-
修改CMakeLists.txt
# 设置CMake最低版本 cmake_minimum_required(VERSION 3.16) # 设置项目名称及版本 project(Tutorial VERSION 1.0) # 生成可执行文件 add_executable(Tutorial main.cc) # 设置选项 option(USE_MYMATH "use Turotial math" ON) # 配置文件:拷贝文件到另一位置,并且修改其内容 configure_file(TutorialConfig.h.in TutorialConfig.h) if(USE_MYMATH) add_subdirectory(MathFunctions) list(APPEND extra_libs MathFunctions) # list(APPEND extra_includes "${PROJECT_SOURCE_DIR}/MathFunctions") 修改1 endif() target_link_libraries(Tutorial PUBLIC ${extra_libs}) # 打印信息 message("PROJECT_BINARY_DIR=${PROJECT_BINARY_DIR}") # 增加include路径到目标,否则会无法include生成的TutorialConfig.h target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}") # 修改2
二 构建
- 结果与CMake Tutorial2_2无差异。
三 Github
- 代码已上传Github