Search code examples
buildmeson-build

How to print a Meson message when a target is built?


In Meson, after building firmware , I have a run_target which prints the size of the firmware. I'd like to print that info to the screen. This can be done via message (capturing the text from run_command). But I'd like to do it when, but only when, I rebuild the firmware.

How can I tell Meson: After building target X, print this message?


Solution

  • The builtin message() is only for configure-time, e.g. when you run meson setup. You are wanting something to be done at build-time, e.g. when you're compiling and linking sources. As you noted, run_target() is a valid way of achieving this, but run_target() will only ever run when invoked by name. In general, as of meson v1.2.0 there would not be a particularly clean way of forcing this to happen, however there is a particularly hacky solution by means of custom_target()...

    firmware = executable(...)
    custom_target(
      'display-firmware-size',
      input:   firmware,
      output:  'firmware-size',
      command: [print_size_to_stderr, '@INPUT@'],
      capture: true # captures stdout to the file, thereby creating it
    )
    

    where the print_size_to_stderr variable is an external program like...

    #!/usr/bin/env bash
    >&1 stat --printf="%s" $1
    

    (command taken from https://unix.stackexchange.com/a/16644)

    If you just use plain old ninja -C <build> or meson compile -C <build>, then if the firmware rebuilds, the display-firmware-size target is marked as needing to be rebuilt, which will print some bits to stderr, and then create a file. The file will keep the task from re-running until the firmware changes again. It's a bit gross but if this is a key thing you want, it would get you across the wire