[CMake] Generating dependencies with gcc -M

Michael Hertling mhertling at online.de
Mon Jun 28 13:09:21 EDT 2010


On 06/28/2010 05:24 AM, Tom Birch wrote:
> CMake's dependency scanner uses its own parser to scan for #include directives, and then builds up the dependency tree this way. I know it's possible to rig up an invocation of gcc -M to generate the correct dependencies, and then feed this into the OBJECT_DEPENDS property of source files, but that means that dependency generation would happen when running 'cmake .', not 'make'.

One compelling reason why dependency scanning is delayed until building
time is that it's taking dynamically generated files into account, i.e.
files not being present at configuration time. Look at the following
CMakeLists.txt:

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(DYNDEP C)
FILE(WRITE ${CMAKE_BINARY_DIR}/f.h "void f(void);\n")
FILE(WRITE ${CMAKE_BINARY_DIR}/f.c "\#include \"f.h\"\nvoid f(){}\n")
FILE(WRITE ${CMAKE_BINARY_DIR}/main.c.in
    "\#include \"f.h\"\nint main(void){f(); return 0;}\n"
)
ADD_CUSTOM_COMMAND(
    OUTPUT main.c
    COMMAND cp main.c.in main.c
    DEPENDS ${CMAKE_BINARY_DIR}/main.c.in
)
INCLUDE_DIRECTORIES(".")
ADD_EXECUTABLE(main ${CMAKE_BINARY_DIR}/main.c ${CMAKE_BINARY_DIR}/f.c)

After cmaking, when running make, the dependency of main.c.o on f.h is
figured out, and this couldn't be achieved during the configuration as
main.c doesn't exist at that time.

> I guess the bigger question here is: why doesn't cmake use gcc -M internally when it's available? It's vastly superior to any homegrown parser, so why not use it?

My assumption is: As gcc or other tools for dependency scanning like
makedepend are not available or desired on all systems supported by
CMake there's a need for an in-house solution, at least as fallback,
and if you once have to provide such a solution why not using it
thoroughly? Besides, this reduces the dependencies on external
programs - one of CMake's strengths.

Regards,

Michael


More information about the CMake mailing list