Build a Project with CMake

In this article, I will talk about how to compile a project with CMake. I create a sample project directory via command promt from Windows:

After that I will create two different folders called source and build in this directory seperately:
I will create a new file called CMakeLists.txt in Source directory. We must do it because we set how CMake should compile the project from the CMakeLists.txt file.

Let's go to the Build directory and run the CMake command:
Setting CMake
I typed cmake -G "MinGW Makefiles" ../Source command like in above. After this command, CMake will generate Makefiles into the Build directory. If you notice I used MinGW Makefiles. This is a generator that CMake supports one of the generators. I use Windows, therefore I used MinGW in my computer. If you use Ubuntu distro you can use Unix Makefiles as generator for CMake.

In the command, I specified the path of Source to reach CMakeLists.txt and we created Makefile script for our project via -G option.

I got a warning about usage of CMakeLists.txt, because I didn't add project() command in CMakeLists.txt. I'll mention it here shortly.

Let's open Build directory and we can see what CMake generated:
I opened CMakeLists.txt and I typed this lines:
cmake_minimum_required(VERSION 3.22.0)

So I want to build an example program. I will type a C++ program as an example:
#include <iostream>

int main()
    std::cout << "Hello World!" << std::endl;

    return 0;
Open CMakeLists.txt again and let's add executable as an output program with this command:
cmake_minimum_required(VERSION 3.22.0)


add_executable(${PROJECT_NAME} main.cpp)
That's fine, but I want to the create with different way now like in the below:
CMake build Source
Now we have to build target with make command. At first I need to go inside of Build directory:
We built target successfully. Now let's run it:
CMake Execute Command

No comments:

Post a Comment