DannyS
DannyS

Reputation: 277

Cmake doesn't recognize custom command as valid source

I have a problem modifying existing CMake based build-system. All I want to do is add different build rule for some of .c files. For the sake of this problem, I will focus on only one file.

The simplified directories tree looks like this

Project:

./src
 - file_of_interest.c
 - CmakeFiles.txt
other_files.c
CmakeFiles.txt

So in order to compile file_of_interest.c in a different way I do:

add_custom_command(
        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.s
        COMMAND xt-xcc -S ${CMAKE_CURRENT_SOURCE_DIR}/file_of_interest.c
        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/file.c
        COMMENT "Generating file_of_interest.s"
    )
add_custom_command(
        OUTPUT  ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.c.o
        COMMAND xt-xcc ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.s -o file_of_interest.c.o -c
        DEPENDS  ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.s
        COMMENT "Generating file_of_interest.c.o"
    )

message(" ${CMAKE_CURRENT_BINARY_DIR} \n ${CMAKE_CURRENT_SOURCE_DIR}")

target_sources(target_name PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.c.o)

As you can see I used CMake's message() to print paths to be sure all is set up properly. It should work, but it doesn't! I expect CMake to register file_of_interest.c.o as source of target_name (and this is probably working), then "tie" it with my custom command which produces OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.c.o and then to tie again ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.c.o with OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.s and this certainly doesn't happen as CMake shows error message saying CMake Error at CMakeLists.txt:170 (add_executable): Cannot find source file: path/file_of_interest.c.o

The path is OK. So the question is why does CMake cannot recognize recipes for that file?

Upvotes: 4

Views: 1315

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65870

It seems that you create an executable (call add_executable) in the top-level CMakeLists.txt, but add_custom_command are called from the subdirectory (src/CMakeLists.txt).

This doesn't work: when CMake processes add_executable and searches for the commands generating its sources, it sees only add_custom_commands created in the same CMakeLists.txt.

From the add_custom_command documentation:

A target created in the same directory (CMakeLists.txt file) that specifies any output of the custom command as a source file is given a rule to generate the file using the command at build time.

It is unrelated that target_sources is called from the same directory as add_custom_command: the target is created by add_executable command, and target_sources just modifies its properties.

Upvotes: 6

Related Questions