13

When using the Autotools it's common to generate a config.h file by specifying the AC_CONFIG_HEADERS macro in configure.ac like this:

AC_CONFIG_HEADERS([config.h])

What is the respective equivalent for this when using CMake?

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
lanoxx
  • 12,249
  • 13
  • 87
  • 142
  • 1
    See [specific](https://cmake.org/cmake/help/v3.0/command/configure_file.html) and [general](http://www.vtk.org/Wiki/CMake:How_To_Write_Platform_Checks) documentation. – Mike Kinghan Jul 17 '16 at 10:02
  • 1
    Possible duplicate of [CMake: How to check header files and library functions like in Autotools?](http://stackoverflow.com/questions/647892/cmake-how-to-check-header-files-and-library-functions-like-in-autotools) – usr1234567 Jul 17 '16 at 16:19

1 Answers1

14

You have to create a file similar to config.h.in. Something like

#cmakedefine HAVE_FEATURE_A @Feature_A_FOUND@
#cmakedefine HAVE_FEATURE_B @Feature_B_FOUND@
#cmakedefine HAVE_FEATURE_BITS @B_BITSIZE@

Then you have to declare the variables Feature_A_FOUND, Feature_B_FOUND, B_BITSIZE in your CMake code and call

configure_file(config.h.in config.h)

which will result in a config.h file similar to the one from the autotools. If a variable is not found or is set to false, the line will be commented. Otherwise the value will be inserted. Assume Feature_A_FOUND=A-NOTFOUNDΒΈ Feature_B_FOUND=/usr/lib/b, B_BITSIZE=64, which will result in

/* #undef HAVE_FEATURE_A @Feature_A_FOUND@ */
#define HAVE_FEATURE_B /usr/lib/b
#define HAVE_FEATURE_BITS 64

Probably HAVE_FEATURE_B would be better defined as #cmakedefine01 which results in 0 or 1 depending on the value of the variable.

In general it is possible to create every config.h file generated by Autotools as CMake is more flexible. But it requires more work and you cannot automatically get a config.h, but you have to write the .in file yourself.

Documentation: https://cmake.org/cmake/help/v3.6/command/configure_file.html

usr1234567
  • 21,601
  • 16
  • 108
  • 128
  • 1
    `#cmakedefine` works only if both identifier and value match i.e. `#cmakedefine MY_VAR @MY_VAR@` works as expected, but `#cmakedefine ABC @MY_VAR@` led to `/* #undef ABC */`, since only `MY_VAR` was a variable (`ABC` wasn't). Doing `#define ABC @MY_VAR@` worked instead. Great answer though; helped me. Thanks! – legends2k Mar 24 '21 at 08:06