MrBit
MrBit

Reputation: 300

cmake override compile definitions from command line

I have a project with cmake and I want to set a compile definition that the user can override from command line every time the make command runs, and set it to whatever they want. I want this to be a string.

I tried to add

add_compile_definitions(USER_DEFINITION)

and run make USER_DEFINITION="HELLO" VERBOSE=1

But I see that the compiler ignores my setting as a string and it just defines it like a boolean.

arm-none-eabi-gcc -DUSER_DEFINITION

I tried to omit the add_compile_definition but I get error: 'USER_DEFINITION' undeclared

Is there any way I can do that in cmake? I could use cmake arguments but I don't want to reconfigure cmake every time.

Upvotes: 2

Views: 2411

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65928

Since a variable in a Makefile is referred with $(varname) syntax, you may write

add_compile_definitions(USER_DEFINITION=$(USER_DEFINITION))

That way, building the project with

make USER_DEFINITION="HELLO"

will pass -DUSER_DEFINITION=HELLO option to the compiler.

Note, however:

  1. This is undocumented feature. It could work in current CMake version and could break in the future versions.

  2. Changing value of the variable does NOT enforce Make to rebuild the executable. That is, if you run make USER_DEFINITION="HELLO" and then make USER_DEFINITION="GOODBAY", the second invocation won't rebuild the executable with the new macro value. You need to explicitly call make clean or make <path-to-object-file> for rebuild the executable.

  3. This works only with Makefile-related generators (build systems). E.g. working for Ninja could require other reference to the variable.

Upvotes: 4

Related Questions