Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use (a config file for) external header files that contain compile time dependend #defines?

Tags:

c++

cmake

Imagine I am compiling (a static) library libfoo.a that provides a header file foo.h. I will link my application APP against libfoo.a and #include <foo.h> in my source code. libfoo is using CMake as a build system with user defined variables, such as BUILD_WITH_OPTION_BAR that are passed on as definitions to the compiler:

ADD_DEFINITIONS(BUILD_WITH_OPTION_BAR)

Inside foo.h we will find #ifdef declarations using this option:

#ifdef BUILD_WITH_OPTION_BAR
   typedef long long int fooInt;
#else
   typedef int fooInt;
#endif

My question is: How am I supposed to know inside my APP that libfoo.a was build with or without BUILD_WITH_OPTION_BAR?

In other words: Where and when do I have to define BUILD_WITH_OPTION_BAR inside my APP?

My basic understanding is that the library libfoo should provide some kind of config.h file that is included inside foo.h, but how do you get an optional #define BUILD_WITH_OPTION_BAR in there at compile time (of libfoo)?

I found this related question: add_definitions vs. configure_file but it doesn't discuss how this is actually accomplished.

like image 614
Chris Avatar asked Oct 18 '22 05:10

Chris


1 Answers

The way to do it is to create a "config.h" file with the defines instead of passing them as command-line arguments to the compiler. You can the distribute the config.h file with the library file.

Cmake provides a mechanism for generating such a file.

CONFIGURE_FILE(<src filename>, <dest filename>)

Typically the source file is named "config.h.in" and the output file is named "config.h". In the .in file lines like this:

#cmakedefine BUILD_WITH_OPTION_BAR 1

are replaced with

#define BUILD_WITH_OPTION_BAR 1

if the option is enabled, otherwise they're commented out.

See https://cmake.org/cmake/help/v3.0/command/configure_file.html and http://www.vtk.org/Wiki/CMake:How_To_Write_Platform_Checks for more.

like image 189
kfsone Avatar answered Oct 31 '22 20:10

kfsone