Source doesn't exist yet for target depending on custom target using source generated by add_custom_command

I am trying to port a meson project to CMake. I have the following subdirectories in my main CMake file:

add_subdirectory(protos)
add_subdirectory(qtlayershell)
add_subdirectory(demo)

and the following in protos/CMakeLists.txt:

set(PROTOCOLS
    ${WAYLAND_PROTOCOL_DIR}/stable/xdg-shell/xdg-shell.xml
    wlr-layer-shell-unstable-v1.xml'
)

foreach(XML ${PROTOCOLS})
    get_filename_component(BASENAME ${XML} NAME_WE)
    add_custom_command(
        OUTPUT  ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/wayland-${BASENAME}-protocol.c
        COMMAND wayland-scanner private-code ${XML} @OUTPUT@
    )
    add_custom_command(
        OUTPUT  ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/wayland-${BASENAME}-protocol.h
        COMMAND wayland-scanner client-header ${XML} @OUTPUT@
    )

    add_custom_command(
        OUTPUT  ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/qwayland-${BASENAME}.h
        COMMAND qtwaylandscanner client-header ${XML} @OUTPUT@
    )
    add_custom_command(
        OUTPUT  ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/${BASENAME}-protocol.cpp
        COMMAND qtwaylandscanner client-code ${XML} @OUTPUT@
    )

    list(APPEND PROTOCOL_SRC
        ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/wayland-${BASENAME}-protocol.c
        ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/${BASENAME}-protocol.cpp
    )

    list(APPEND PROTOCOL_HEADERS
        ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/qwayland-${BASENAME}.h
        ${CMAKE_CURRENT_BINARY_DIR}/wayland-protos/wayland-${BASENAME}-protocol.h
    )
endforeach()


set(WAYLAND_PROTOCOL_SRC ${PROTOCOL_SRC} PARENT_SCOPE)
set(WAYLAND_PROTOCOL_HEADERS ${PROTOCOL_HEADERS} PARENT_SCOPE)

add_custom_target(wayland_protocols DEPENDS ${WAYLAND_PROTOCOL_SRC} ${WAYLAND_PROTOCOL_HEADERS})

and in qtlayershell/CMakeLists.txt, a target like this:

add_library(qtlayershell SHARED
    ${QTLAYERSHELL_SRC}
    ${WAYLAND_PROTOCOL_SRC}
    DEPENDS wayland_protocols
)

But I am getting an error that somelongbuildpath/protos/wayland-protos/wayland-xdg-shell-protocol.c doesn’t exist yet. Here is full error:

  Cannot find source file:

    /home/noone/KDE/my/build-qtlayershell-Desktop-Debug/protos/wayland-protos/wayland-xdg-shell-protocol.c

  Tried extensions .c .C .c++ .cc .cpp .cxx .cu .m .M .mm .h .hh .h++ .hm
  .hpp .hxx .in .txx


CMake Error at qtlayershell/CMakeLists.txt:9 (add_library):
  No SOURCES given to target: qtlayershell
CMake Generate step failed.  Build files cannot be regenerated correctly.
CMake process exited with exit code 1.

here is the full project on github https://github.com/VioletSith/qtlayershell

Scope visibility between add_custom_command and targets can be a bit weird. I’d recommend moving the add_custom_command calls to be beside the target (not made by add_custom_target) that will use them.

This discussion has some relevant details for that.