Cmake (2) - set, message and if
這次要介紹的 Cmake 功能有 set, message 跟 if。
1. 專案結構:
cpp hpp 的內容可以參考 Cmake (0) - 簡單 Project
lib/CmakeLists.txt 的內容可以參考Cmake (1) - add_subdirectory
.
├── CmakeLists.txt
├── build
├── include
│   └── greet.hpp
├── lib
│   ├── CmakeLists.txt
│   └── greet.cpp
└── src
    └── main.cpp
2. 專案主 CmakeLists.txt:
編輯專案主 CmakeLists.txt。
.
├── CmakeLists.txt
├── build
├── include
│   └── greet.hpp
├── lib
│   ├── CmakeLists.txt
│   └── greet.cpp
└── src
    └── main.cpp
專案主要的 CmakeLists.txt 設定如下。我們定義一個變數 USE_GREET,下面的 if 會參考 USE_GREET 決定編譯的方式。
當 USE_GREET = True 時會編譯執行檔 main。message 可以用來確認變數的值。
cmake_minimum_required(VERSION 3.11.0)
project(HELLO_CMAKE)
set(USE_GREET True)
message(STATUS "USE_GREET: " ${USE_GREET})
if(USE_GREET)
    add_subdirectory(lib)
    target_include_directories(greet PUBLIC include)
    add_executable(main src/main.cpp)
    target_link_libraries(main greet)
endif()
跑一下 Cmake 及 make 確定 main 有被 build 出來。
$ cd build $ cmake .. $ make
3. Cached variable:
編輯專案主 CmakeLists.txt。
cmake_minimum_required(VERSION 3.11.0)
project(HELLO_CMAKE)
set(USE_GREET True CACHE BOOL "Description")
message(STATUS "USE_GREET: " ${USE_GREET})
if(USE_GREET)
    add_subdirectory(lib)
    target_include_directories(greet PUBLIC include)
    add_executable(main src/main.cpp)
    target_link_libraries(main greet)
endif()
Cached variable 在已定義的情形下不會複寫既有的值,我們可以在執行 Cmake 時定義變數。
$ cd build $ rm -fr * $ cmake -D USE_GREET=False ..
Cmake 執行過程會出現 USE_GREET: False 然後我們可以 make 看看,這時候 main 不會被 build 出來。
4. 結論:
一般來說需要透過外部進行修改或設定的變數就會使用 cache。
 
留言
張貼留言