cmake ignoring CMAKE_INSTALL_PREFIX inside CMakeLists.txt

Viewed 317

I have a small project with a very simple CMakeLists.txt file. At the bottom of this file, I have the following lines:

set (CMAKE_INSTALL_PREFIX  /opt/myprod)
message (STATUS "CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}")
install (TARGETS myprod DESTINATION bin)

However, when I run:

sudo make install

I get the following:

[100%] Built target myprod
Install the project...
-- Install configuration: ""
-- Up-to-date: /usr/bin/myprod
-- Up-to-date: /usr/bin/myprod

cmake always puts my executable under /usr/bin when it should be under /opt/myprod/bin. And, yes, the last line is always repeated. Does anyone know how I can fix this?

Using cmake 3.20.3 on Fedora 34.

1 Answers

Your issue cannot be reproduced with the level of detail you've given:

File CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)
project(myprod)

add_executable(myprod main.cpp)

set(CMAKE_INSTALL_PREFIX /opt/myprod)
message (STATUS "CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}")
install (TARGETS myprod DESTINATION bin)

File main.cpp

int main() { return 0; }

Commands:

$ cmake -S . -B build
...
$ cmake --build build/
$ sudo cmake --build build/ --target install
[sudo] password for alex:
[0/1] Install the project...
-- Install configuration: "Release"
-- Installing: /opt/myprod/bin/myprod
$ sudo rm -rf /opt/myprod/

So as you can see, /opt/myprod survived to the final output.


The install() command is responsible for generating the cmake_install.cmake script in the build directory. As far as I know, the very first one reads CMAKE_INSTALL_PREFIX, so you must have another call to install() in your project that you aren't showing us.

Furthermore, you should not set CMAKE_INSTALL_PREFIX inside the CMakeLists.txt; it is designed to be set externally as a cache variable. Hard-coding it is bad because someone else might wish to install your project to a different location besides /opt. Maybe they're on a different operating system or Linux distribution. Maybe even your whims change. In any case, one shouldn't need to edit a file to change the install prefix.

Since you're using CMake 3.20, I strongly encourage you to move such settings to presets.

Related