【问题标题】:Cmake doesn't recognize custom command as valid sourceCmake 无法将自定义命令识别为有效源
【发布时间】:2020-01-09 11:09:09
【问题描述】:

我在修改现有的基于 CMake 的构建系统时遇到问题。我想要做的就是为一些 .c 文件添加不同的构建规则。为了这个问题,我只关注一个文件。

简化的目录树如下所示

项目:

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

所以为了以不同的方式编译 file_of_interest.c:

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)

如您所见,我使用 CMake 的 message() 来打印路径以确保所有设置都正确。它应该工作,但它没有!我希望 CMake 将 file_of_interest.co 注册为 target_name 的源(这可能是有效的),然后将其与生成 OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.c.o 的自定义命令“绑定”,然后将 ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.c.o 与 OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/file_of_interest.s 再次绑定,这当然不会发生,因为 CMake 显示错误消息说 CMake Error at CMakeLists.txt:170 (add_executable): Cannot find source file: path/file_of_interest.c.o

路径没问题。那么问题是为什么 CMake 无法识别该文件的配方?

【问题讨论】:

    标签: gcc build cmake


    【解决方案1】:

    您似乎在顶级 CMakeLists.txt 中创建了一个可执行文件(调用add_executable),但add_custom_command 是从子目录(@ 987654325@)。

    这不起作用:当 CMake 处理 add_executable 并搜索生成其源的命令时,它只会看到在 same CMakeLists.txt 中创建的 add_custom_commands

    来自add_custom_commanddocumentation

    同一目录CMakeLists.txt文件)中创建的目标将自定义命令的任何输出指定为源文件,并给出生成文件的规则在构建时使用该命令。

    target_sourcesadd_custom_command在同一目录中调用无关:目标add_executable命令创建,target_sources只是修改其属性。

    【讨论】:

    • 确实如此。顺便说一句,有没有办法让 cmake 进行构建的中间步骤?例如,我想使用显式阶段 *.c -> *.s -> *.o -> binary
    • 我不知道在编译链接链中添加额外步骤的方法。但是您使用add_custom_command 生成目标文件的方式实际上是一个好方法。只需确保此 add_custom_commandadd_executable 在同一 CMakeLists.txt 中发布即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2019-08-27
    • 1970-01-01
    • 2015-07-25
    • 2016-09-07
    • 2018-12-02
    • 1970-01-01
    相关资源
    最近更新 更多