yorel
yorel

Reputation: 323

cmake: setting how a specific file is compiled

In my YOMM2 library, I have a file called lab.cpp (declared in the CMakeLists.txt here), to experiment with new features. Since the library uses complex macro techniques, I would like that specific file to be compiled in two steps:

  1. preprocess with -E, sending the output, filtered though clang-format, to an intermediate file
  2. compile the intermediate file, producing lab.cpp.o

After quite a bit of googling, I cannot find how to do that. Even worse, while playing with add_custom_command, my cmake (v 3.16.3) does not recognize the OUTPUT parameter.

Help please?

Upvotes: 0

Views: 565

Answers (1)

KamilCuk
KamilCuk

Reputation: 140880

I would like that specific file to be compiled in two steps:

How to do that

A simple solution would be to add a add_custom_command with the preprocessor, then feed the output to the compiler.

cmake_minimum_required(VERSION 3.11)
project(test)
add_custom_command(
   OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/file.c
   DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/file.c
   COMMAND gcc -E -o ${CMAKE_CURRENT_BINARY_DIR}/file.c ${CMAKE_CURRENT_SOURCE_DIR}/file.c
)
add_executable(test ${CMAKE_CURRENT_BINARY_DIR}/file.c)

results in:

$ cmake -S. -B_build . && cmake --build _build -v
...
[ 33%] Generating file.c
gcc -E -o /dev/shm/.1000.home.tmp.dir/_build/file.c /dev/shm/.1000.home.tmp.dir/file.c
[ 66%] Building C object CMakeFiles/test.dir/file.c.o
/usr/bin/cc    -MD -MT CMakeFiles/test.dir/file.c.o -MF CMakeFiles/test.dir/file.c.o.d -o CMakeFiles/test.dir/file.c.o -c /dev/shm/.1000.home.tmp.dir/_build/file.c
...

A great and amazing solution would be to add a custom compiler to CMake that handles your own custom extension in a way you want. That compiler would be just a wrapper around real compiler to do the processing you want.

Upvotes: 1

Related Questions