Menu Share

How to setup CMake for C++ (Windows)

by | Last Updated:
C++

Save Share Print

In this article I will provide you with the information on how to setup CMake and compile your C++ project. You may also use this to compile third-party projects and solutions that you depend upon.

Table of Contents

What do you need to follow through this tutorial

  • You would need to have some basic knowledge of C++ as I will not be explaining why or what the application that we are compiling does. Start from this post that explains the basics of C++.
  • There are some terminal commands being executed but you will not need previous knowledge on Command Prompts / PowerShell. Check out this post on how to operate the command line.
  • Visual Studio installed with support for C++ compilation. CMake will automatically detect your Visual Studio installation later.

Why do we need CMake?

C++ is an old language. Do not make a mistake it is really powerful and provides a lot of control over low level memory and system programming. As an old language though it misses some of the modern high-level language concepts. When programming in C++ it is hard to target multiple platforms as there is no unified project structure as well as good package management.

On other languages like Java, C# and python the code is always compiled to an intermediate language or is interpreted directly at runtime. That code is then run by a special virtual machine that translates it to commands for the specific machine.

This is what CMake strives to solve but the other way around. It is a project generator. On Windows one would want to work with Visual Studio project files and solutions and on Linux one would rather have Make files. This essentially means that we unify our project files under CMake which on the other hand generates the project files for the specific system.

Read more: You can check out more on how the compiler and linker work to gain in depth knowledge on why the process is different than other languages.

Install CMake

To install cmake you open this page: https://cmake.org/download/

You should find the corresponding binary for your windows installation (x64, x86) and download the .msi file. It should roughly look something like this:

CMake Download

The install wizard is pretty straightforward just make sure that on the question “By default CMake does not add its directory to the system PATH” you check one of the options Add CMake to system Path so that later we can execute commands from the windows terminal.

Creating our project

We will have the most simple example for our first compile using CMake. We will start as always with our “Hello, World!” application using a single .cpp file to demonstrate how CMake will generate a project and compile that file.

We will have the following project structure:

root
├── src/
│  └── main.cpp
└── CMakeLists.txt

In our “main.cpp” file we will write down the following “Hello, World!” application:

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

The “CMakeLists.txt” file is our base of operations when using CMake. It can link other CMakeLists files which later on will make it easy to include dependency (vendor) projects and compile them along our application. We will start with the most basic content for our file so that we can compile our “main.cpp” into a simple console application:

# This will set the minimum version of CMake required to generate the projects
# CMakeLists has its own language and features and as more and more versions are 
# added it will include new keywords and options
cmake_minimum_required(VERSION 3.18) 

# This will give our project a name
project(Main)

# This instructs CMake that we want to generate an executable file from this project
# Other options would be add_library but this is a topic for another time
# You can notice that we also pass on the path to our cpp file
add_executable(Main src/main.cpp)

How to generate build files

To start generating the cmake projects we will need to open a terminal window inside the root folder where our CMakeLists.txt file resides. This can easily be done by clicking shift + right mouse button inside the folder and then selecting “Open PowerShell window here”. After we’ve done that we can execute the following commands:

mkdir build
cd build
cmake ..

This will create the directory build, then move the terminal working directory to build and then generate projects using the “CMakeLists.txt” file in the previous directory as noted by the two dots after cmake (single dot means current directory, two dots means one directory up).

You can also specify the source and build directories by adding the following flags:

cmake -B [build directory] -S [source directory]

After executing this command the “build” folder will be filled with project files. Double clicking the “Main.sln” file would open up Visual Studio. If you’ve followed up until now you would have 3 projects in the solution explorer as follows:

Visual Studio Generated Projects
  • Main – this is the project that we want to build and that will generate our executable.
  • ALL_BUILD – by default this will be set up as the startup project and it will run Main and ZERO_CHECK.
  • ZERO_CHECK – as our project is not actually controlled by visual studio but generated externally we cannot add source/header files inside of visual studio itself. To do that we would need to append them into the add_executable command inside of “CMakeLists.txt”. The ZERO_CHECK project would then monitor for changes in that file and regenerate VS projects based on the changes.

Now that we have Visual Studio open we can build the project. Use the shortcut ctrl + shift + b to run the build command or click on the top menu “Build” -> “Build Solution”.

Visual Studio Build Solution

Note: If you still have the command line open you can also use the command

cmake --build . --config Debug

You can run the project by right clicking on the “Main” project in Visual Studio solution explorer and selecting the option “Set as Startup Project”. On the top navigation bar you will notice a play button with the label of “Local Windows Debugger” that you can click to run your project (shortcut is ctrl + F5).

Note: If you’ve built the project using the command line you can run the application that we just compiled by using the following commands:

cd Debug .\Main.exe

Adding more source files

To add other files to the project you would need to create them in the target directory using Windows Explorer and then add them to CMakeLists. Lets say for example that we decide to move the “#include <iostream>” and all future includes into another file. We also want to create a header file called “main.h” and another C++ file called “other.cpp” resulting in the following following changes:

root
├── build/
│  └── Generated Build Files
├── src/
│  ├── main.h
│  ├── main.cpp
│  └── other.cpp
└── CMakeLists.txt

Create a file called main.h in the src directory with the following content

void print_hello_world();

Then we modify main.cpp to include main.h instead of <iostream> and also call the newly defined function. This would result into the following file:

#include "main.h"

int main() {
    
print_hello_world();
    return 0;
}

Lets also add another file that would implement the print_hello_world function and call it other.cpp:

#include <iostream>

void print_hello_world() {
    std::cout << "Hello, World!" << std::endl;
}

At this point visual studio would not be able to compile the project as it will not know about other.cpp. It would be able to find the main.h file. To fix this we need to open CMakeLists.txt and modify the following line:

add_executable(Main src/main.cpp src/other.cpp src/main.h)

Though it is no need to add the header file it is a good practice to list all source files so that you can also see them listed in the solution explorer later.

You can now run build. Visual Studio will display a prompt if you want to reload the projects. Be sure to click on “Reload All”.

Using CMake GUI to build

To use the visual CMake application is even easier. As CMake is already installed on Windows you can open the “Start” menu and start typing “cmake”. Select the “CMake (cmake-gui)” that should appear as a search result.

Search for CMake in Start Menu

After you open it a window will appear where you can put on some options for generating the project files. First thing you should locate the “Where is the source code” input field and select the folder where your project resides (the root CMakeLists.txt file). Then you can select a directory where the projects will be generated by giving a value to the “Where to build the binaries”. In my case I create a separate directory but you can also just write the path to the “build” directory again. After these two fields are filled in you can click on the “Generate” button bellow. It should look something like this:

CMake GUI Window

After the projects are generated you can repeat the steps above for the new directory “build-gui”. You will also have the option to click on the “Open Project” button in the CMake GUI Window.

Using Visual Studio 2017/2019

On the latest versions of visual studio you can open alternatively open the root directory with Visual Studio. It will automatically detect that it is a CMake type of project. The benefit of opening the solution this way is that Visual Studio will not actually generate a solution. It will use another build system called “Ninja” that I will talk about in another post. This system is faster on rebuilds which makes it more efficient to compile C++ code.


You can follow up with:

Save Share Print

Leave a comment