1

我的顶级 CMakeLists.txt 中有这个:

add_subdirectory (src) # add_executable (${PROJECT_NAME} ${_SOURCES})
add_subdirectory (data)

在数据子目录中,我想在构建 ${PROJECT_NAME} 时创建一个文件。以下不起作用,返回目标“foo”不存在:

add_custom_command(
        OUTPUT "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.desktop"
        WORKING_DIRECTORY "${PROJECT_BINARY_DIR}"
        COMMAND ${INTLTOOLMERGE} -d -u ../po ${PROJECT_NAME}.desktop.in "${PROJECT_NAME}.desktop"
        COMMENT "Creating desktop file"
        DEPENDS ${PROJECT_NAME}
    )

这也行不通。返回:目标名称“foo”在此上下文中是未知的

add_custom_command(
        TARGET ${PROJECT_NAME}
        WORKING_DIRECTORY "${PROJECT_BINARY_DIR}"
        COMMAND ${INTLTOOLMERGE} -d -u ../po ${PROJECT_NAME}.desktop.in "${PROJECT_NAME}.desktop"
        COMMENT "Creating desktop file"
    )

但这按预期工作:

add_custom_command(
        OUTPUT "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.desktop"
        WORKING_DIRECTORY "${PROJECT_BINARY_DIR}"
        COMMAND ${INTLTOOLMERGE} -d -u ../po ${PROJECT_NAME}.desktop.in "${PROJECT_NAME}.desktop"
        COMMENT "Creating desktop file"
    )
    add_custom_target (desktopfile DEPENDS "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.desktop")
    add_dependencies (${PROJECT_NAME} desktopfile)

问题:

1.- 在不使用目标的情况下构建“foo”时,如何使用 add_custom_command 运行命令?

2.- add_dependencies 怎么知道“foo”但纯 add_custom_command 不知道?

更新#1:简单代码:

# /CMakeLists.txt
cmake_minimum_required (VERSION 3.0)
project ("foo")

add_subdirectory (src)
add_subdirectory (data)

# : EOF~

# src/CMakeLists.txt
add_executable (${PROJECT_NAME} main.c)

# : EOF:~

# data/CMakeLists.txt

add_custom_command (
    TARGET ${PROJECT_NAME}
    POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E sleep 5
    COMMENT "We're going to try to pause here for 5 seconds"
)

# EOF:~

# src/main.c
#include <stdio.h>

int main () {
    printf ("Hello world");
    return 0;
}
4

1 回答 1

4

请使用 POST_BUILD 选项。

从 cmake 文档:

 add_custom_command(TARGET target
                     PRE_BUILD | PRE_LINK | POST_BUILD
                     COMMAND command1 [ARGS] [args1...]
                     [COMMAND command2 [ARGS] [args2...] ...]
                     [WORKING_DIRECTORY dir]
                     [COMMENT comment] [VERBATIM])

这定义了一个与构建指定目标相关联的新命令。该命令何时发生取决于指定以下哪一项:

PRE_BUILD - 在所有其他依赖项之前运行 PRE_LINK - 在其他依赖项之后运行 POST_BUILD - 在构建目标之后运行

请注意,仅 Visual Studio 7 或更高版本支持 PRE_BUILD 选项。对于所有其他生成器,PRE_BUILD 将被视为 PRE_LINK。

于 2015-05-06T05:36:06.123 回答