When working with CMake, keeping the build directory clean is important to avoid stale or conflicting object files, especially when switching build configurations. Instead of manually deleting the build directory or its contents, CMake provides convenient ways to clean up the build artifacts safely. This tutorial demonstrates how to clean build directory using CMake.
Let's say we have a minimal CMake project in the CMakeLists.txt
file:
cmake_minimum_required(VERSION 3.27)
project(myapp)
set(CMAKE_CXX_STANDARD 17)
add_executable(${PROJECT_NAME} main.cpp)
Run the following command to generate the necessary build files before starting the build:
cmake -S . -B build
Next, you can build the project by running:
cmake --build build
Sometimes, you want to clean out all generated build files before rebuilding. CMake provides two useful options for this:
- Clean build directory
You can clean the build directory by running:
cmake --build build -t clean
This tells the build system to run its clean
target, which deletes all compiled files and intermediate objects but keeps the generated build files (like Makefile
or project files).
After cleaning, you can rebuild as usual:
cmake --build build
- Clean first before building
Alternatively, you can use the --clean-first
option:
cmake --build build --clean-first
This will first clean the build directory (like the previous command) and then immediately build the project in one step.
Leave a Comment
Cancel reply