This post is part of a modern CMake tutorial: table of contents.
Modern CMake 101: Introduction
CMake is a cross-platform build system generator, tool to test and package applications. Over the years, it gained attention and now it is widespread. It can even be used in Visual Studio, from 2017 version up, out of the box. Over the years, CMake language has grown and philosophy of writing good build script has changed. There are many tutorials for writing CMake build scripts, but even the official one is outdated and doesn't show modern practices. This post summarizes key facts about creating modern CMake scripts.The first thing to do is to use recent enough version of CMake, ie. at least 3.0. Without it, one cannot follow best practices. See cmake_minimum_required.
The second thing is to forget about global variable, global compiler flags and thinking about directories. Modern CMake is all about modules and treating targets as objects. Targets have:
- named constructors:
- properties
- member functions
Because targets should be viewed as objects, one should carefully consider which parts of target create its interface and which are internal and used only to build a given target. There are three kinds of target properties:
- INTERFACE - properties creating an interface of target and used to build other targets depending on considered one.
- PRIVATE - private properties of the target, needed only to build target and should not be propagated to other targets.
- PUBLIC - properties which are both: INTERFACE and PRIVATE.
The third thing to keep in mind, when using a modern build tool, is to think about target dependencies and not about compile flags and directories. For expressing, that one target depends on the other, use target_link_libraries. As with all target data, one should carefully consider whether targets dependency should be in interface or not. To properly use targets from a different project, one should always export library interface with help of the install command and its exports mode.
No comments:
Post a Comment