LINK_DEPENDS on output of add_custom_command, no rule to make target

Hi, I have a project that lives in a subdirectory example of another project, can’t figure out why it keeps on complaining that:

No rule to make target ‘example/linkerscript.ld’, needed by ‘example/example’. Stop.

Here’s the code

cmake_minimum_required(VERSION 3.8)

project("example" LANGUAGES C)

add_executable(example main.c)

add_custom_command(
    OUTPUT  ${CMAKE_CURRENT_BINARY_DIR}/linkerscript.ld
    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/generate_linkerscript.sh
    COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/generate_linkerscript.sh ${CMAKE_LINKER} ${CMAKE_CURRENT_BINARY_DIR}/linkerscript.ld
    COMMENT Generates linkerscript with custom sections
)
add_custom_target(linkerscript DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/linkerscript.ld)

set_target_properties(example PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/linkerscript.ld)
target_link_options(example PRIVATE -T${CMAKE_CURRENT_BINARY_DIR}/linkerscript.ld)

Here’s the tree of the directory:

├── example
│   ├── CMakeLists.txt
│   ├── generate_linkerscript.sh
│   └── main.c

If I manually build the target linkerscript, then building example succeeds, however if I clean and just try building example I’m getting the error from the beginning.

This should have been pretty simple but it’s really frustrating.

Any help would be welcome!

Your example executable target has no dependency on the ${CMAKE_CURRENT_BINARY_DIR}/linkerscript.ld or the linkerscript target. Adding the following line should fix your problem:

add_dependencies(example linkerscript)

I see, can you please explain why the following line wasn’t enough:

set_target_properties(example PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/linkerscript.ld)

Thanks

I missed that you were setting the LINK_DEPENDS property. I see why you’re confused, that appears like it should have worked. Can you confirm you’re using one of the Makefiles generators or Ninja?

Using Unix Makefiles I’m getting this behavior.

However using Ninja it seems to build correctly, interesting.

Adding

add_dependencies(example linkerscript)

Resolves the issue for Makefiles however.

This seems like a regression then. Could you please open a bug report to track it.

This is probably due to Ninja generators having a global graph where everything is visible. The Makefiles generators have some “fences” that hide rules in one subgraph from other subgraphs.