CMake source_group and generated files interaction

Viewed 322

For a project I am autogenerating multiple Fortran source files using add_custom_command. To my knowledge this results in CMake creating a GENERATED source file that I can add to a target such as a library or executable. However, since the file does not exist at CMake compile time CMake cannot use the source_group command to group these generated files for the IDE (Visual Studio).

Is there another way to achieve the same result as source_group that I cannot find? For example when using CMake with Qt you can set the AUTOGEN_SOURCE_GROUP to change the source group for the automoc and autorcc generated files.

Example.

# Creates a command to generate the 'a.f90' file using 'mytool.exe' and 'a.f90.in'. 
add_custom_command(
    OUTPUT a.f90
    COMMAND mytool.exe a.f90.in
    DEPENDS a.f90.in
)

add_executable(example a.f90 b.f90 c.f90) # Where b.f90 and c.f90 are not generated

source_group("Source Files/Not Generated" FILES "b.f90 c.f90")
source_group("Source Files/Generated" FILES a.f90) # Does nothing

This results in the following visual studio filters,

Source Files
|- Non Generated Files
   |- b.f90
   |- c.f90
|- a.f90

instead of

Source Files
|- Non Generated Files
   |- b.f90
   |- c.f90
|- Generated Files
   |- a.f90
1 Answers

To help others who might be trying the same thing. Here's my workaround. I couldn't find a way to group autogenerated files using add_custom_command. This leaves a possible solution. If you are fine with not having the files autogenerated when your code is compiled you may instead use the execute_process command. With execute_process the command will be run when CMake creates the build tree instead of when you compile your source code. Since the files will already exist may be added as normal source files and can be grouped using source_group.

Example

# Generates 'a.f90'
execute_process(COMMAND mytool.exe a.f90.in ${CMAKE_CURRENT_BINARY_DIR}/a.f90)

add_executable(main "${CMAKE_CURRENT_BINARY_DIR}/a.f90" b.f90 c.f90)

source_group("Source Files/Not Generated" FILES "b.f90 c.f90")
source_group("Source Files/Generated" FILES a.f90)

With this the visual studio filters look like

Source Files
|- Generated
  |- a.f90
|- Not Generated
  |- b.f90
  |- c.f90

Related