Search code examples
cmake

CMake: generate header using custom tool output


I'm porting some obscure library from autotools to cmake.

The library in question compiles custom tool that outputs header into stdout, and this header is used later in the project.

How can I port that to cmake?

I can compile "header generator" using

add_executable(generator generator.c)

But how can I run it and redirect its output to header file using cmake? I'll also need dependency handling of course... (i.e. if generator.c changes, generator must be recompiled and header must be regenerated).


Solution

  • The add_custom_command allows you to execute a command during the cmake process to produce an output at build time. Here is an example where it outputs foo.c into ${CMAKE_BINARY_DIR} (the folder where your target build is placed) by copying bar.c from ${CMAKE_CURRENT_SOURCE_DIR} (the current folder being processed)

    add_custom_command(
      OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/foo.c
      COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/bar.c ${CMAKE_CURRENT_BINARY_DIR}/foo.c
      DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/bar.c
    )
    add_executable(foo foo.c)
    

    See this page from gitlab for more information: "How can I generate a source file during the build?"