CMake教程版本號:3.16.3
英文原文鏈接: https://cmake.org/cmake/help/latest/guide/tutorial/index.html#id2
github示例代碼 https://github.com/sxpsxp12/cmake-learning-exampes
添加自檢
我們的代碼有時候會使用平臺相關的一些實現,我們該怎麼去判定這些接口存不存在呢?
我們可以通過宏來校驗是否存在該相關的符號。
include(CheckSymbolExists)
set(CMAKE_REQUIRED_LIBRARIES "m")
check_symbol_exists(log "math.h" HAVE_LOG)
check_symbol_exists(exp "math.h" HAVE_EXP)
configure_file(config.h.in config.h)
target_include_directories(helloworld
PUBLIC "${CMAKE_BINARY_DIR}"
INTERFACE ${CMAKE_SOURCE_DIR}
)
然後,在配置頭文件中添加定義,以將CMake結果傳遞到頭文件
// does the platform provide exp and log functions?
#cmakedefine HAVE_LOG
#cmakedefine HAVE_EXP
最後,構建
cd build
cmake ..
make
指定編譯定義
在配置頭文件中增加編譯定義,相比較,更好的方式是直接使用target_compile_definitions
。我們不再需要此類的配置頭文件了。
include(CheckSymbolExists)
set(CMAKE_REQUIRED_LIBRARIES "m")
check_symbol_exists(log "math.h" HAVE_LOG)
check_symbol_exists(exp "math.h" HAVE_EXP)
if(HAVE_LOG AND HAVE_EXP)
target_compile_definitions(helloworld PRIVATE "HAVE_LOG" "HAVE_EXP")
endif(HAVE_LOG AND HAVE_EXP)
target_include_directories(helloworld
INTERFACE ${CMAKE_SOURCE_DIR}
)
總結
本節我們學到的CMake命令有
include
所屬:腳本指令,總是可用的
加載並運行CMake代碼或者模塊
include(<file|module> [OPTIONAL] [RESULT_VARIABLE <var>]
[NO_POLICY_SCOPE])
具體描述: https://cmake.org/cmake/help/latest/command/include.html
target_compile_definitions
所屬:項目命令,只能用於CMake項目
給可執行程序添加編譯定義
target_compile_definitions(<target>
<INTERFACE|PUBLIC|PRIVATE> [items1...]
[<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
-D之後的項會被移除,空的項會被忽略
target_compile_definitions(foo PUBLIC FOO)
target_compile_definitions(foo PUBLIC -DFOO) # -D removed
target_compile_definitions(foo PUBLIC "" FOO) # "" ignored
target_compile_definitions(foo PUBLIC -D FOO) # -D becomes "", then ignored
歡迎各位大佬右側點贊、關注、打賞,我們再會。。。