[CMake] Question about add_custom_command

Michael Hertling mhertling at online.de
Thu Sep 9 22:04:20 EDT 2010


On 09/09/2010 06:53 PM, David Aldrich wrote:
> Hi 
> 
> As mentioned before, I am replacing a manually built gnu makefile (for Linux) that builds a library, with CMake.
> 
> A required build step is to run an executable called versionInfo that processes all the source files of the library and generates a new source file called SourceFileInfo.cpp. This generated file must be compiled and added to the library. This step must be executed when any library dependency changes (i.e. any other source file changes).
> 
> I tried:
> 
> add_custom_command (
>   TARGET Kernel
>   PRE_BUILD
>   COMMAND ${CMAKE_SOURCE_DIR}/../VersionInfo/versionInfo ${CMAKE_SOURCE_DIR} KERNEL
>   [COMMENT "Building SourceFileInfo.cpp"]
>   )                    
> 
> add_library(Kernel STATIC
>             ErrorHandler.cpp
>             EnvVars.cpp
>             SourceFileInfo.cpp
>             <snip>
>             )
> 
> The source files are compiled ok, but versionInfo does not run and, because SourceFileInfo.cpp is therefore not found, the script fails.
> 
> Am I on the right track?
> 
> I read that PRE_BUILD is only supported for Visual Studio 7 or later, but I got no better result with PRE_LINK.

Use the other signature of ADD_CUSTOM_COMMAND(), cf. FAQ 4.6:

ADD_CUSTOM_COMMAND(
    OUTPUT SourceFileInfo.cpp
    COMMAND .../versionInfo ...
    DEPENDS <all files to trigger a regeneration of OUTPUT>)

For an example, look at the following CMakeLists.txt:

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(GENDEP C)
FILE(WRITE ${CMAKE_BINARY_DIR}/g.c "void g(void){}\n")
ADD_CUSTOM_COMMAND(
    OUTPUT ${CMAKE_BINARY_DIR}/f.c
    COMMAND echo "void f(void){}" > ${CMAKE_BINARY_DIR}/f.c
    DEPENDS ${CMAKE_BINARY_DIR}/g.c
    VERBATIM)
FILE(WRITE ${CMAKE_BINARY_DIR}/main.c "int main(void){f();return 0;}\n")
ADD_EXECUTABLE(main main.c f.c)

"f.c" is regenerated and, thus, "main" rebuilt if "g.c" is touched
although it's not incorporated in "main". Btw, if versionInfo is a
target within your project you don't need to specify its location
on disk after COMMAND; the target's name suffices in that case.

Regards,

Michael


More information about the CMake mailing list