CMake override cached variable using command line
Solution 1
I found two methods for changing CMake variables.
The first one is suggested in the previous answer:
cmake -U My_Var -D Mu_Var=new_value
The second approach (I like it some more) is using CMake internal variables. In that case your variables will be still in the CMake cache, but they will be changed with each cmake
invocation if they are specified with -D My_Var=...
. The drawback is that these variables would not be seen from GUI or from the list of user's cache variables. I use the following approach for internal variables:
if (NOT DEFINED BUILD_NUMBER)
set(BUILD_NUMBER "unknown")
endif()
It allows me to set the BUILD_NUMBER
from the command line (which is especially useful on the CI server):
cmake -D BUILD_NUMBER=4242 <source_dir>
With that approach if you don't specify your BUILD_NUMBER
(but it was specified in previous invocations), it will use the cached value.
Solution 2
You could use
CMake -UMy_Var -DMy_Var=new_value
see documentation https://cmake.org/cmake/help/v3.9/manual/cmake.1.html
I hope this helps.
Related videos on Youtube
TomP89
Hi, I'm a software engineer with experience mainly in C++ and C#. I also have a strong interest in image processing and visual intelligence. I live in sunny old England and support the mighty Burnley football club Cheers
Updated on September 15, 2022Comments
-
TomP89 over 1 year
As I understand it, when you provide a variable via the command line with
cmake
(e.g.-DMy_Var=ON
), that variable is stored inside the cache. When that variable is then accessed on future runs of the CMake script, it will always get the value stored inside the cache, ignoring any subsequent-DMy_Var=OFF
parameters on the command line.I understand that you can force the cache variable to be overwritten inside the CMakeLists.txt file using
FORCE
or by deleting the cache file, however I would like to know if there is a nice way for the-DMy_Var=XXX
to be effective every time it is specified?I have a suspicion that the answer is not to change these variables within a single build but rather have separate build sub-dirs for the different configs. Could someone clarify?
-
avtomaton over 4 yearsSo why is it downvoted? It is one of the really good solutions for the described problem.
-
Wang about 2 yearsno this is not true, if in cmake file you have turn on the CACHE option for the variables, it won't get overwritten at all.
-
HQW.ang about 2 years@Wang Can you be more specific about CACHE option? Stick to the example I listed, I add
set(Foo "initial value" CACHE STRING "A string")
before themessage
line, I can still change its value on each invocation of cmake command line.