深入理解CMake

Effective Modern CMake

Getting Started

For a brief user-level introduction to CMake, watch C++ Weekly, Episode 78, Intro to CMake by Jason Turner. LLVM’s CMake Primer provides a good high-level introduction to the CMake syntax. Go read it now.

After that, watch Mathieu Ropert’s CppCon 2017 talk Using Modern CMake Patterns to Enforce a Good Modular Design (slides). It provides a thorough explanation of what modern CMake is and why it is so much better than “old school” CMake. The modular design ideas in this talk are based on the book Large-Scale C++ Software Design by John Lakos. The next video that goes more into the details of modern CMake is Daniel Pfeifer’s C++Now 2017 talk Effective CMake (slides).

This text is heavily influenced by Mathieu Ropert’s and Daniel Pfeifer’s talks.

If you are interested in the history and internal architecture of CMake, have a look at the article CMake in the book The Architecture of Open Source Applications.

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.

Define project properties globally.

For example, a project might use a common set of compiler warnings. Defining such properties globally in the top-level CMakeLists.txt file prevents scenarios where public headers of a dependent target causing a depending target not to compile because the depending target uses stricter compiler options. Defining such project properties globally makes it easier to manage the project with all its targets.

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.

Get your hands off CMAKE_CXX_FLAGS.

Different compilers use different command-line parameter formats. Setting the C++ standard via -std=c++14 in CMAKE_CXX_FLAGS will brake in the future, because those requirements are also fulfilled in other standards like C++17 and the compiler option is not the same on old compilers. So it’s much better to tell CMake the compile features so that it can figure out the appropriate compiler option to use.

Don’t abuse usage requirements.

As an example, don’t add -Wall to the PUBLIC or INTERFACE section of target_compile_options, since it is not requ

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ztenv

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值