How to define a C++ preprocessor macro through the

2019-01-14 06:43发布

问题:

I try to set a preprocessor macro in the command line of CMake. I've tried:

set generator="Visual Studio 8 2005"
set params=-D MY_MACRO=1
cmake.exe -G %generator% %params% ..\some_project

but it's neither defined when I compile nor can I find the name MY_MACRO in the files generated by CMake at all, except for CMakeCache.txt where it's present in the form:

MY_MACRO:UNINITIALIZED=1

How can I do it?

回答1:

A good alternative would be to define a cmake option:

OPTION(DEFINE_MACRO "Option description" ON) # Enabled by default

Followed by a condition:

IF(DEFINE_MACRO)
    ADD_DEFINITIONS(-DMACRO)
ENDIF(DEFINE_MACRO)

Then you can turn that option ON/OFF via command line with cmake using the -D flag. Example:

cmake -DDEFINE_MACRO=OFF ..

To make sure the compiler is receiving the definition right, you can call make in verbose mode and check for the macro being defined or not:

make VERBOSE=1

This is a good solution also because make will recompile your code when any of cmake options changes.



回答2:

Try this: -D CMAKE_CXX_FLAGS=/DMY_MACRO=1



回答3:

Unless you have a good reason not to, you should use ADD_DEFINITIONS(<name>=<value>[, ...]).

Just add the following line to your CMakeLists.txt:

ADD_DEFINITIONS("MY_MACRO=1")

CMake will take care of the syntax of the switches (be it -D<name>=<value>, or /D<name>=<value>).



标签: c++ cmake