Search code examples
linuxshellcmakepost-build

Shell commands using Cmake add_custom_command on Linux


I can't figure out the right syntax to run a shell command in a post-build step in Cmake on Linux. I can make a simple echo work, but when I want to e.g. iterate over all files and echo those, I'm getting an error.

The following works:

add_custom_command(TARGET ${MY_LIBRARY_NAME}
                   POST_BUILD
                   COMMAND echo Hello world!
                   USES_TERMINAL)

This correctly prints Hello world!.

But now I would like to iterate over all .obj files and print those. I thought I should do:

add_custom_command(TARGET ${MY_LIBRARY_NAME} 
                   POST_BUILD
                   COMMAND for file in *.obj; do echo @file ; done 
                   VERBATIM
                   USES_TERMINAL)

But that gives the following error:

/bin/sh: 1: Syntax error: end of file unexpected

I've tried all sorts of combinations with quotation marks or starting with sh, but none of that seems to work. How can I do this correctly?


Solution

  • add_custom_command (and all the other CMake functions that execute a COMMAND) don't run shell scripts, but only allow the execution of a single command. The USES_TERMINAL doesn't cause the command to be run in an actual terminal or allow the use of shell builtins like the for loop.

    From the documentation:

    To run a full script, use the configure_file() command or the file(GENERATE) command to create it, and then specify a COMMAND to launch it.

    Or, alternatively, for very simple scripts you can do what @lojza suggested in the comment to your question and run the bash command with the actual script content as an argument.

    add_custom_command(
      TARGET ${MY_LIBRARY_NAME}
      POST_BUILD 
      COMMAND bash -c [[for file in *.obj; do echo ${file}; done]]
      VERBATIM
    )
    

    Note that I deliberately used a CMake raw string literal here so that ${file} is not expanded as a CMake variable. You could also use bash -c "for file in *obj; do echo $file; done" with a regular string literal, in which case $file also isn't expanded due to the lack of curly braces. Having copied and pasted bash code from other sources into CMake before I know how difficult it is to track down bugs caused by an unexpected expansions of CMake variables in such scripts, though, so I'd always recommend to use [[ and ]] unless you actually want to expand a CMake variable.

    However, for your concrete example of doing something with all files which match a pattern there is an even simpler alternative: Use the find command instead of a bash loop:

    add_custom_command(
      TARGET ${MY_LIBRARY_NAME}
      POST_BUILD 
      COMMAND find
        -maxdepth 1 
        -name *.obj 
        -printf "%P\\n"
      VERBATIM
    )