Skip to content

Build commands details using CMAKE

Debraj Das edited this page Mar 7, 2026 · 1 revision

How to build C++ project using CMAKE

Command 1: The Configuration Phase

cmake -S . -B build

This step does not compile your code. Instead, it reads your CMakeLists.txt "recipe," figures out what operating system you are on, finds your libraries (like Crow and CPR), and generates all the messy configuration files needed to compile the project.

  • cmake: Calls the CMake program.
  • -S . (Source): This tells CMake where your source code and CMakeLists.txt are located. The . means "look right here in the current directory."
  • -B build (Build): This is the magic flag. It tells CMake, "Do not dump all your messy generated files in my main folder. Create a new folder named build and put everything in there." This is called an "out-of-source build" and it keeps your project root clean.

Analogy: This is like the architect drawing up the blueprints and clearing out the construction site.


Command 2: The Compilation Phase

cmake --build build

This is the step that actually turns your .cpp files into a runnable application.

  • cmake: You are calling CMake again, but this time you are using it as a wrapper to trigger your actual compiler (like g++ or make).
  • --build build: This tells CMake, "Go inside that build folder you made in step 1, read the generated instructions, and actually compile the code." Analogy: This is the construction crew showing up, reading the blueprints, and actually building the house.

Why is it done this way?

If you just ran g++ main.cpp, it does both steps at once. But by splitting them up, CMake becomes cross-platform. If you run cmake -S . -B build on your Debian machine, it generates a Linux Makefile. If a friend runs that exact same command on Windows, it automatically generates a Visual Studio project for them instead. Then, cmake --build build knows exactly how to trigger the right tools on either machine!

Basic CMakeLists file for back-end development (CPR, CROW)

# 1. State the minimum CMake version required (usually 3.10 or higher)
cmake_minimum_required(VERSION 3.15)

# 2. Name your project and optionally set the C++ standard (like C++17)
project(MyAwesomeServer)
set(CMAKE_CXX_STANDARD 17)

# 3. Tell CMake what libraries you need from your computer
# (REQUIRED means CMake will stop and warn you if it can't find them)
find_package(cpr REQUIRED)
find_package(Crow REQUIRED)

# 4. Create your executable (Name it 'server', built from 'main.cpp')
add_executable(server main.cpp)

# 5. Link the libraries to your executable
target_link_libraries(server PRIVATE cpr::cpr Crow::Crow)