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