Part 1: Setting up a basic C++ project using CMake and Make for building

Step 1 - Create a working directory

Open a terminal, navigate to a suitable directory and run the following commands:

$ mkdir tutorial
$ cd tutorial

This will create an empty directory called tutorial inside which we'll be working.

Step 2 - Add a minimal C++ program

Create a new file in tutorial called main.cpp and fill it with the following piece of code:

int main() {
    return 0;
}

The above is a small C++ program with a basic main function that doesn't do anything (for now).

Step 3 - Add a CMakeLists.txt file

Create a new file in tutorial called CMakeLists.txt.

Set the minimum CMake version required to 3.13. While we don't need such a high CMake version right now, we'll need it in later parts of the tutorial.

cmake_minimum_required(VERSION 3.13 FATAL_ERROR)

Set project details, primarily the language to let CMake know that this is a C++ project.

project(tutorial VERSION 0.0.1 LANGUAGES CXX)

Add a new executable target with our main program above.

add_executable(tutorial
    main.cpp
)

Once you have followed the above instructions, you should have a CMakeLists.txt that looks like this:

cmake_minimum_required(VERSION 3.13 FATAL_ERROR)
project(tutorial VERSION 0.0.1 LANGUAGES CXX)

add_executable(tutorial
    main.cpp
)

Step 4 - Build

Create a new build directory in tutorial for running any build commands. It is a good practice to follow so that any files produced as a result of building do not pollute the original project.

$ mkdir build
$ cd build

Run CMake to generate a Makefile.

$ cmake .. -DCMAKE_BUILD_TYPE=Release

Run Make to build the executable.

$ make

Check if everything above worked without errors.

Step 5 - Run executable

There should be an executable named tutorial in the build directory. It does nothing for now, but we can still run it using

./tutorial

Conclusion

In this part, we learnt how to create a new C++ project that uses CMake and Make for building. In the next part we will learn how to add the Marlin Multicast SDK to the project using CMake.