cmake add_custom_command和DEPENDS / TARGET

时间:2015-05-03 22:16:29

标签: cmake add-custom-command

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

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

在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;
}

1 个答案:

答案 0 :(得分: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。