When working with CMake-based projects, it's common to control where the compiled files, headers, and other assets are installed. By default, CMake installs targets under system locations, such as /usr/local on Linux or C:/Program Files/${PROJECT_NAME} on Windows. However, during development or testing, you often want to install them somewhere else - for example, into a temporary directory. This tutorial explains how to set installation prefix using CMake.
Let's say we have the following CMakeLists.txt file:
cmake_minimum_required(VERSION 3.27)
project(myapp)
set(CMAKE_CXX_STANDARD 17)
add_executable(${PROJECT_NAME} main.cpp)
install(TARGETS ${PROJECT_NAME})
We can define the installation prefix when generating the build files by setting the CMAKE_INSTALL_PREFIX variable:
cmake -S . -B build -DCMAKE_INSTALL_PREFIX=/tmp/app
This tells CMake that all installed files should go under /tmp/app. We can also use a relative path (for example install/app) instead of an absolute one - in that case, the path is interpreted relative to the current build directory.
Build the project as usual:
cmake --build build
After the build completes, the executable will be inside the build directory, but it's not installed yet.
Now run to install files:
cmake --install build
You should see an output similar to:
-- Install configuration: ""
-- Installing: /tmp/app/bin/myapp
This means the program was installed to the /tmp/app/bin, since executables are placed in the bin subdirectory of the specified installation prefix.
CMake also allows you to override the prefix without reconfiguring the project using --prefix option when installing files:
cmake --install build --prefix build
Output example:
-- Install configuration: ""
-- Installing: /home/john/myproject/build/bin/myapp
In this case, the --prefix option temporarily replaces the prefix specified during configuration.
Leave a Comment
Cancel reply