Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make cmake pass command line variable to compiler

Tags:

c++

cmake

I have following code:

int main() {
#ifdef COMMIT_VERSION
   cout << "app version: " << COMMIT_VERSION << endl;
#endif
}

I would like to invoke cmake such that it passes COMMIT_VERSION variable defined on command line to g++ and thus to my application. E.g. following invocation:

cmake -WHAT_IS_THE_OPTION_NAME COMMIT_VERSION='"Hello Version"'
make
./a.out

produces output

app version: Hello Version
like image 566
Trismegistos Avatar asked Aug 08 '14 16:08

Trismegistos


People also ask

How do you pass arguments in CMake?

Modify your cache variable to a boolean if, in fact, your option is boolean. If you create the cache variable in the CMakeLists. txt file and then pass the argument via calling cmake, won't the CMakeList.

How use CMake command line?

Running CMake from the command line From the command line, cmake can be run as an interactive question and answer session or as a non-interactive program. To run in interactive mode, just pass the option “-i” to cmake. This will cause cmake to ask you to enter a value for each value in the cache file for the project.


1 Answers

You can use the -D <var>:<type>=<value> option to add a definition within the cmake script (type and value being optional), like so:

cmake -D COMMIT_VERSION='"whatever version here"' ...

Then, inside the script, you can use the add_definitions function to pass the definition to g++:

add_definitions(-DCOMMIT_VERSION=${COMMIT_VERSION})
like image 123
Drew McGowen Avatar answered Oct 26 '22 01:10

Drew McGowen