How to get access cmake variable in a header file

I want want to access a cmake variable in a header file. I was able to use add_compile_definition() to create a preprocessor definition based on a cmake variable that I could use in a cpp file, but when I try the same mechanism in a header file it doesn’t work.

You’ll want configure_file() for this:

#cmakedefine DEF_OR_UNDEF
#cmakedefine DEF_WITH_VALUE @value@
#cmakedefine01 TRUE_OR_FALSE


set(DEF_OR_UNDEF 0) # will be `// #undef DEF_OR_UNDEF`
set(value 5)
set(DEF_WITH_VALUE 1) # will be `#define DEF_WITH_VALUE 5`
set(TRUE_OR_FALSE OFF) # will be `#define TRUE_OR_FALSE 0`
1 Like

Thanks Ben. To be clear, those #cmakedefine statements need to go into a *.in.h file which configure_file() will then use to create a header file which I need to include? Said otherwise, there’s no getting around creating another header file?

Yes, they should go on the source side of the configure_file command. And no, you need to communicate through a header file (or some other files that is #include’d).