CMake, copy source files expand macros and build

1.7k Views Asked by At

I need to do following.

Source code is located in

src\MY_SOURCE_PATH\SourceFiles

I need to expand macros, especially because I use macros to generate some source code (guards for serializing enums in example, also the same thing is done by some libraries I use (Offirmo, SparkParticleEngine) but I don't want macros polluting my users namespace nor write a lot of code by hand.

So I need to preprocess some macros (not all, for example I don't want to expand things like "assert" or include guards) and create a clone of my source dir.

src_expanded\MY_SOURCE_PATH\SourceFilesWithLessMacros

then I would run "build" on that new directory, and finally I want to move headers that match a particular REGEX (headers prefixed with "libraryPrefix") on a Include Directory

include\MY_SOURCE_PATH\HeadersMarkedAsPublicIncludes

so that users cannot include implementation headers

1

There are 1 best solutions below

0
Angew is no longer proud of SO On BEST ANSWER

Expanding only some macros sounds rather complicated. If you'd be content with just "I want to generate some parts of the file" in a different way than preprocessor macros, you could use CMake's command configure_file.

What the command does is parse a file and substitute CMake variables inside the file. Here's an example of what your configured.cpp file might look like:

#include <cassert>

void ${SET_BY_CMAKE}(int x) {
  assert(x == 42);
}

In CMakeLists.txt, you'd do the following:

set(SET_BY_CMAKE foo)
configure_file(configured.cpp configured.cpp)
add_executable(MyExe ${CMAKE_CURRENT_BINARY_DIR}/configured.cpp other.cpp files.cpp)

The call to configure_file will create a configured.cpp file in your binary directory which will look like this:

#include <cassert>

void foo(int x) {
  assert(x == 42);
}