0

I am using a variable that I want the user to be able to pass using the command line. However, the variable is not overridden as I was expecting. The reference doc I am using is Cmake Cache

My CMakeLists.txt looks like this

cmake_minimum_required(VERSION 3.23.0)

project(design_principles)

set(PRINCIPLE "solid/single_responsibility" CACHE STRING "Enter the principle to be run" FORCE)

message(${PRINCIPLE})

add_executable(
    ${PROJECT_NAME}
    ${PRINCIPLE}.cpp
    )

target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17)

The command I am passing through the command line is

cmake -S . -B build -DPRINCIPLE=temp

However, it appears that the build is always using the default value from CMakeLists.txt

The Guru
  • 55
  • 6
  • Does this answer your question? [How to overwrite macro definition in CMake](https://stackoverflow.com/questions/41866614/how-to-overwrite-macro-definition-in-cmake) – Ryan Zhang May 18 '22 at 06:59
  • 1
    _Why_ did you use `FORCE`? – tkausl May 18 '22 at 07:00
  • @tkausl The document mentioned this about the `FORCE` option. "The FORCE option will cause the set command to override and change the cache value of a variable." – The Guru May 18 '22 at 07:02
  • 4
    Yeah, so? Thats exactly what you don't want. – tkausl May 18 '22 at 07:04
  • Ah. See. I think I misunderstood the `FORCE` option from the docs. I thought it to mean that the user-defined value will be forced to over-ride the existing cache variable value. Thanks for the clarification – The Guru May 18 '22 at 07:20

1 Answers1

0

From the documentation:

Since cache entries are meant to provide user-settable values this does not overwrite existing cache entries by default. Use the FORCE option to overwrite existing entries. [...] If the cache entry does not exist prior to the call or the FORCE option is given then the cache entry will be set to the given value.

The problem is clear: since you have written FORCE, the set() command will always overwrite the cache entry. The solution is to simply get rid of FORCE:

set(PRINCIPLE "solid/single_responsibility" 
    CACHE STRING "Enter the principle to be run")
Alex Reinking
  • 16,724
  • 5
  • 52
  • 86