...

/

CMake Command: Generating a Project Build System

CMake Command: Generating a Project Build System

Let's learn about the commands to generate the project build system in CMake.

This is the first step required to build our project. Here are a few options in terms of how the CMake build action can be executed:

Press + to interact
cmake [<options>] -S <path-to-source> -B <path-to-build>
cmake [<options>] <path-to-source>
cmake [<options>] <path-to-existing-build>

One important feature of CMake is the support for out-of-source builds or the production of artifacts in a separate directory. In contrast to tools such as GNU Make, this ensures the source directory is kept clean from any build-related files and avoids polluting our Version Control Systems (VCS) with unnecessary files or ignoring directives. This is why it's best to use the first form of command of generation mode:

Note: Specify the path to the source tree with the -S option, followed by the path to the directory of the produced buildsystem, specified with -B:

cmake -S ./project -B ./build

The preceding command will generate a buildsystem in the ./build directory (or create it if it’s missing) from the source in the ./project directory.

We can skip one of the arguments, and cmake will “guess” that we intended to use the current directory for it. However, watch out. Skipping both will get an in-source build, and that is messy.

Note: Do not use the second or third form of the cmake <directory> command. This is because it can produce a messy in-source build. As hinted in the syntax snippet, the same command behaves differently if a previous build already exists in <directory>: it will use the cached path to the sources and rebuild from there. Since we often invoke the same commands from the Terminal command history, we might get into trouble here: before using this form, always check whether our shell is currently working in the right directory.

Examples

Build in the current directory, but take the source from one directory up (note that -S is optional):

cmake -S ..
...