0

I want to change the macro value from the command line using CMakeList.txt. I have

#ifndef NUMBER
#define NUMBER  1
#endif

and

#ifndef NAME
#define NAME "MyName"  //string format
#endif

I found some links -> How to define a C++ preprocessor macro through the command line with CMake?. There they say to add add_definitions(-DNUMBER=5) in CMake and it is working I can change the value using this way.

I want some way where I can change the value using command-Line. Like add_definitions(-DNUMBER=NUMBERX) and from command Line we provide the number cmake NUMBERX=100. and NAMEX="ALEXA". Or some other way instead add_definitions().

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
horsemann07
  • 79
  • 1
  • 7
  • It may work if you spelt add_defin**i**tions correctly. There is no a in definitions – cup Jul 17 '21 at 08:09
  • Even the question you refer to has [the answer](https://stackoverflow.com/a/10364240/3440745) with option-approach, which allows to set specific macro definition conditionally, depending from the command line parameter. [The answer](https://stackoverflow.com/a/9533742/3440745) to the duplicate question describes using a command-line value directly as a macro value. – Tsyvarev Jul 17 '21 at 09:47

1 Answers1

1

You could add a cache variable for the user to provide this option at the time of configuring the project. For modifying an existing project I recommend using cmake-gui; cache variables will show up there for you to modify.

set(MY_PROJECT_DEFINITION_NAME "default-value" CACHE STRING "compiler definition for the NAME macro") # you could choose another name for the variable, of course

#I recommend adding the definition on a per-target basis, but it could be used with add_definitions too
target_compile_definitions(my_project PRIVATE "NAME=${MY_PROJECT_DEFINITION_NAME}") # another visibility may be appropriate

Configure your project using

cmake -D "MY_PROJECT_DEFINITION_NAME=non-default-value" -S source_dir_path -B build_dir_path

Leaving you -D "MY_PROJECT_DEFINITION_NAME=non-default-value" will result in MY_PROJECT_DEFINITION_NAME taking the value of default-value.

You may want to take a look at the exact syntax/type options in the documentation of the set command btw.

fabian
  • 80,457
  • 12
  • 86
  • 114