CMake:add_custom_command与PRE_BUILD不起作用

时间:2014-10-06 12:48:26

标签: c++ linux cmake add-custom-command

在下面的CMakeLists.txt文件中,虽然我已经设置了add_custom_command命令PRE_BUILD,但在制作主可执行文件之前并不总是执行自定义命令:

cmake_minimum_required(VERSION 2.8)
project(VersioningTest)

set(MAJOR 1)
set(MINOR 0)
set(PATCH 0)

set(PRODUCT App-${MAJOR}-${MINOR}-${PATCH})

ADD_EXECUTABLE(${PRODUCT}
                main.cpp
                Engine.cpp)

add_custom_command(TARGET ${PRODUCT} PRE_BUILD
                COMMAND ${CMAKE_COMMAND}
                -DMAJOR=${MAJOR}
                -DMINOR=${MINOR}
                -DPATCH=${PATCH}
                -P ${CMAKE_SOURCE_DIR}/SetVersion.cmake
                WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
                COMMENT "setting version...")

所以我决定将add_custom_command替换为add_custom_targetadd_dependencies

add_custom_target(SetVersion
                COMMAND ${CMAKE_COMMAND}
                -DMAJOR=${MAJOR}
                -DMINOR=${MINOR}
                -DPATCH=${PATCH}
                -P ${CMAKE_SOURCE_DIR}/SetVersion.cmake
                WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
                COMMENT "setting version...")

add_dependencies(${PRODUCT} SetVersion)

它有效。现在每次执行SetVersion.cmake文件之前执行主可执行文件。我的CMake文件中add_custom_command出了什么问题?

SetVersion.cmake档案的内容:

EXECUTE_PROCESS(
    COMMAND svn info ${CMAKE_SOURCE_DIR}
    COMMAND grep Revision
    OUTPUT_VARIABLE REVISION
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

EXECUTE_PROCESS(
     COMMAND svn diff ${CMAKE_SOURCE_DIR}
     OUTPUT_VARIABLE SVNDIFF
     OUTPUT_STRIP_TRAILING_WHITESPACE
 )

if(SVNDIFF STREQUAL "")
    set(LOCALCHANGES 0)
    message("No local changes detected")
else(SVNDIFF STREQUAL "")
    set(LOCALCHANGES 1)
    message("Local changes detected!")
endif(SVNDIFF STREQUAL "")

configure_file(${CMAKE_SOURCE_DIR}/version.h.in ${CMAKE_SOURCE_DIR}/version.h)
message("Version set") # For testing only

version.h.in的内容:

#define MAJOR_VERSION "${MAJOR}"
#define MINOR_VERSION "${MINOR}"
#define PATCH_VERSION "${PATCH}"
#define REVISION "${REVISION}"
#define LOCALCHANGES "${LOCALCHANGES}"

1 个答案:

答案 0 :(得分:5)

这取决于您使用的CMake生成器。以下是add_custom_command文档中的相关部分:

Note that the PRE_BUILD option is only supported on Visual Studio 7 or later.
For all other generators PRE_BUILD will be treated as PRE_LINK.

在OS X下PRE_BUILD似乎也适用于Xcode,但没有正确记录。