Meluha
Meluha

Reputation: 1578

Passing an argument to CMAKE via command prompt

I have a makefile for my project, with which I can pass an argument that controls certain build flags. Now I want to do the same using CMake. I have created CMakeLists.txt but I don't know how to pass the argument and check for the argument value in CMakeLists.txt.

Sample of my Makefile:

ifeq "$(MY_VARIABLE)" "option_value"
      //setting some flags
else
      //setting some other flag
endif

I then call make using make MY_VARIABLE=option_value. What is the way in CMake to take the argument from command prompt and set flags based on that?

Upvotes: 88

Views: 177800

Answers (2)

Peter
Peter

Reputation: 14947

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(MY_VARIABLE "option_value" CACHE STRING "Some user-specified option")

Source: https://cmake.org/cmake/help/latest/command/set.html#set-cache-entry

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line with -D:

cmake -DMY_VARIABLE:STRING=option_value2

Modify your cache variable to a boolean if, in fact, your option is boolean.

Upvotes: 101

PJ_Finnegan
PJ_Finnegan

Reputation: 2181

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

Upvotes: 61

Related Questions