CMake Do's and Don'ts {行為準則}
- 1. General
- 2. Modules
- 3. Projects
- References
Effective Modern CMake
https://gist.github.com/mbinna/c61dbb39bca0e4fb7d1f73b0d66a4fd1
Do’s and Don’ts
https://cliutils.gitlab.io/modern-cmake/chapters/intro/dodonot.html
do's and don'ts = dos and don'ts
1. General
- Use at least CMake version 3.0.0
Modern CMake is only available starting with version 3.0.0.
- Treat CMake code like production code
CMake is code. Therefore, it should be clean. Use the same principles for CMakeLists.txt
and modules as for the rest of the codebase.
把 CMake 程序視作代碼。它應該和其他的代碼一樣,是整潔并且可讀的。
- Use lowercase function names (使用小寫的函數名)
CMake functions and macros can be called lower or upper case. Always use lower case. Upper case is for variables.
CMake 的函數和宏的名字可以定義為大寫或小寫,但是一般都使用小寫,變量名用大寫。
- Forget the commands
add_compile_options
,include_directories
,link_directories
,link_libraries
Those commands operate on the directory level. All targets defined on that level inherit those properties. This increases the chance of hidden dependencies. Better operate on the targets directly.
這些命令在目錄級別上操作。在該級別上定義的所有目標都會繼承這些屬性。這增加了隱藏依賴項的可能性。最好直接在目標上操作。
2. Modules
- Use modern find modules that declare exported targets
Starting with CMake 3.4, more and more find modules export targets that can be used via target_link_libraries
.
3. Projects
- Avoid custom variables in the arguments of project commands
Keep things simple. Don’t introduce unnecessary custom variables. Instead of add_library(a ${MY_HEADERS} ${MY_SOURCES})
, do add_library(a b.h b.cpp)
.
- Don’t use
file(GLOB)
in projects
CMake is a build system generator, not a build system. It evaluates the GLOB
expression to a list of files when generating the build system. The build system then operates on this list of files. Therefore, the build system cannot detect that something changed in the file system.
CMake 是一個構建系統生成器,而不是構建系統。它在生成構建系統時將 GLOB
表達式求值為文件列表。然后構建系統會對此文件列表進行操作。因此,構建系統無法檢測到文件系統中發生了某些變化。
CMake cannot just forward the GLOB
expression to the build system, so that the expression is evaluated when building. CMake wants to be the common denominator of the supported build systems. Not all build systems support this, so CMake cannot support it neither.
CMake 不能直接將 GLOB
表達式轉發給構建系統,以便在構建時評估該表達式。CMake 希望成為受支持的構建系統的 common denominator。并非所有構建系統都支持這一點,因此 CMake 也不能支持它。
References
[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] Quick start guide, https://www.jetbrains.com/help/clion/clion-quick-start-guide.html
[3] 輕松上手, https://www.jetbrains.com/zh-cn/clion/features/start-your-project.html