bison-like tools run in both Debug & Release (in Visual Studio) ?

We have an in-house code generator similar to Bison (generating both h- and cpp-files). We describe it with an add_custom_command() call. The generation of the h/cpp-files is independent of Debug/Release, so I had assumed that CMake + Visual Studio would arrange for the files to be generated just once.

But the behavior I see is:

  • first Debug build → generates the files
  • first Release build → generates the files again
  • later Debug build → no further generation

The CMake fragment we use look like:

add_custom_command(
  OUTPUT
     ${CMAKE_BINARY_DIR}/foo.h
     ${CMAKE_BINARY_DIR}/foo.cpp
  DEPENDS
     ${CMAKE_SOURCE_DIR}/foo.spec
  COMMAND
     ${foogen} ${CMAKE_SOURCE_DIR}/foo.spec --outdir ${CMAKE_BINARY_DIR}
  )

target_sources(prog1 PUBLIC
    prog1.cpp
    ${CMAKE_BINARY_DIR}/foo.h
    ${CMAKE_BINARY_DIR}/foo.cpp
    )

The second generation of the files also causes unnecessary rebuild of other sources depending on the h-file.

Am I using add_custom_command() the wrong way? Or is there a better way to do this?

Regards,
/Johan Holmberg

In VS, the commands are duplicated (IIRC) and stamp files might be used behind the scenes.

A more robust way would be to generate into a temporary file and then cmake -E copy_if_different it into the final location.

Thanks, I will try that.

Currently I have already changed the add_custom_command() to put the output files in a configuration dependent location (via $<CONFIG> generator expression). That way I still get the files generated twice, but “Debug” and “Release” no longer interfer with each other. Not optimal, but better than before for us.

I think a $<CONFIG>-using pattern is likely the simpler solution long-term.