Overwriting option flags CMAKE_RUNTIME_OUTPUT_DIRECTORY, CMAKE_LIBRARY_OUTPUT_DIRECTORY and CMAKE_ARCHIVE_OUTPUT_DIRECTORY

Hello!

I have the following use case:

Lets say the project’s top-level CMakeLists.txt file contains the following lines:

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY, [some-path])
set(CMAKE_RUNTIME_LIBRARY_DIRECTORY, [some-path])
set(CMAKE_RUNTIME_ARCHIVE_DIRECTORY, [some-path])

Is it possible to overwrite these paths at runtime using the command line interface? Per documentation the following commands below can be used to set the paths at runtime. However, my tests show that the paths set at runtime will not overwrite the paths that have been already set within the CMakeLists.txt file.

$ mkdir build && cd build
$ cmake  -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=/my/path -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/my/path -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=/my/path ..
$ cmake --build .

Is there another way, or some option that I am missing to overwrite the paths set within the CMakeLists.txt, without manipulating the CMakeLists.txt file itself?

Thanks in advance!

Setting a variable in a CMakeLists.txt will always take precedence over variable defined on command line.

Variables defined on command lines will be defined as cache variables, and variables defined in CMakeLists.txt are standard variables.

So, you have to check if variable is not yet defined before defining it:

if (NOT DEFINED CMAKE_RUNTIME_OUTPUT_DIRECTORY)
  set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "/my/path")
endif()

By the way, in your example, there is a comma after variable name which is, I suppose, a mistake.

Alternatively, you could do this instead:

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "/my/path" CACHE PATH "Runtime output path")
# ...