[CMake] Following dependencies through generated header file

Michael Hertling mhertling at online.de
Fri Oct 1 18:11:38 EDT 2010


On 10/01/2010 10:56 PM, Óscar Fuentes wrote:
> A file `foo.cpp' has this:
> 
> #include "bar.inc"
> 
> `bar.inc' is a generated file, and is marked as such. It is generated
> processing a file `zoo.cpp' with an utility executed through a custom
> command.
> 
> It would be very convenient to inspect the header files referenced from
> `zoo.cpp' and associate them with `bar.inc', so when some of those
> header files are touched `bar.inc' (and hence `foo.cpp') is
> automatically re-built.
> 
> Is this possible?

Yes, with a bit of trickiness:

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(GENDEP CXX)
FILE(WRITE ${CMAKE_BINARY_DIR}/foo.cpp "#include \"bar.inc\"\n")
FILE(WRITE ${CMAKE_BINARY_DIR}/zoo.cpp "#include \"zoo.h\"\n")
FILE(WRITE ${CMAKE_BINARY_DIR}/zoo.h "#define ZOO_H\n")
ADD_LIBRARY(zoo SHARED zoo.cpp)
ADD_LIBRARY(foo SHARED foo.cpp bar.inc)
ADD_CUSTOM_COMMAND(OUTPUT bar.inc
    COMMAND ${CMAKE_COMMAND} -E touch bar.inc DEPENDS zoo.cpp zoo)

So, zoo.cpp includes zoo.h, the helper target zoo is compiled from
zoo.cpp, and the custom command which generates bar.inc depends on
zoo.cpp as desired, but on the zoo target, too - that's the crucial
moment: If zoo.h is touched, zoo is rebuilt, but the custom command
runs also since one of its dependencies is a library and newer than
its output. AFAIK, files intended to be subject of CMake's built-in
dependency checking must be mentioned in a target's sources, hence
the necessity of the auxiliary zoo target to trigger the generation
of bar.inc if one of zoo.cpp's included headers change.

'hope that helps.

Regards,

Michael


More information about the CMake mailing list