Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a function like macro using CMake

I can't find how to declare function like macros in CMake.

I need a macro function like:

#define MYFUNC(foo) QString( foo + "_suffix" )

to be defined by my CMakeLists.txt file. I tried:

add_definitions("-DMYFUNC(foo)=QString\(foo+\"_suffix\"\)")

and

add_definitions("-DMYFUNC\(foo\)=QString\(foo+\"_suffix\"\)")

but none works, compiler (VS2015) always reports MYFUNC is undefined...

like image 632
jpo38 Avatar asked Apr 03 '20 09:04

jpo38


People also ask

How do you define a macro in Cmake?

If you are using CMake 3. X your first choice for adding a preprocessor macro should be target_compile_definitions. The reason you should prefer this approach over any other approach is because it granularity is target based. IE the macro will only be added to your exe/library.

How do I specify in Cmake?

You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value , just cmake -D var=value or with cmake -C CMakeInitialCache. cmake .

What does Cmake -- Build do?

CMake can generate a native build environment that will compile source code, create libraries, generate wrappers and build executables in arbitrary combinations. CMake supports in-place and out-of-place builds, and can therefore support multiple builds from a single source tree.


2 Answers

From the Visual Studio documentation on /D:

The /D option doesn't support function-like macro definitions. To insert definitions that can't be defined on the command line, consider the /FI (Name forced include file) compiler option.

For completeness, GCC does support defining function macros from the commandline:

If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you should quote the option. With sh and csh, -D'name(args…)=definition' works.

like image 167
Botje Avatar answered Oct 19 '22 13:10

Botje


CMake documentation for COMPILE_DEFINITIONS states explicitly that function-like macros are not supported:

The COMPILE_DEFINITIONS property may be set to a semicolon-separated list of preprocessor definitions using the syntax VAR or VAR=value. Function-style definitions are not supported. CMake will automatically escape the value correctly for the native build system (note that CMake language syntax may require escapes to specify some values).

Consider using -include instead to force inclusion of a header file where your macro is defined.

like image 1
Pavel Kirienko Avatar answered Oct 19 '22 15:10

Pavel Kirienko