[CMake] Add a custom command to all targets

Michael Wild themiwi at gmail.com
Wed Aug 12 10:44:22 EDT 2009


On 12. Aug, 2009, at 15:27, Julien Michel wrote:

> Dear Cmake users,
>
> I would like to add a custom command to be run on each target (in  
> fact on each target source file). Is there any way to do this with  
> cmake ? I found the ADD_CUSTOM_COMMAND function, but it must be  
> called for each target to be processed, and I am still missing a way  
> to get the source files list. Do you have any idea or advice ?
>
> Best regards,
>
> Julien



function( my_custom_add_executable NAME )
   set( OPTIONS )
   set( GENERATED_SOURCES )
   foreach( arg ${ARGN} )
     if( arg MATCHES "(WIN32|MACOSX_BUNDLE|EXCLUDE_FROM_ALL)" )
       list( APPEND OPTIONS arg )
       continue
     endif( arg MATCHES "(WIN32|MACOSX_BUNDLE|EXCLUDE_FROM_ALL)" )
     #TODO define the name of the generated file generated from ${arg}  
in GENERATED
     add_custom_command(
       OUTPUT ${GENERATED}
       COMMAND ${YOUR_COMMAND} ${SOME_FLAGS_GO_HERE} ${arg}
       DEPENDS ${arg}
       COMMENT "Generating ${arg}"
       VERBATIM
       )
     list( APPEND GENERATED_SOURCES ${GENERATED} )
   endforeach( arg )
   # and here goes the actual add_executable call
   add_executable( ${NAME} ${OPTIONS} ${GENERATED_SOURCES} )
endif( my_custom_add_executable )


You then simply replace all calls to add_executable with  
my_custom_add_executable. Similarly you can proceed with add_library.  
If you need to distinguish on source type (i.e. do something different  
for all .c files than you do for all .idl files, you can do so easily  
using a IF( ... MATCHES ... ) sequence in the FOREACH loop.


Michael


More information about the CMake mailing list