使用 CMake 在项目构建文件夹中创建 git 提交 ID 文件

Creating a git commit id file in the project build folder using CMake

  1. 首先,我定义 COMMIT_ID 变量:
    execute_process(COMMAND git rev-parse HEAD
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        OUTPUT_VARIABLE COMMIT_ID )
  1. 如果指定 COMMIT_ID 变量,则项目不会生成:
    add_custom_command(TARGET ${APP_NAME} POST_BUILD
        WORKING_DIRECTORY
            $<TARGET_FILE_DIR:${APP_NAME}>
        DEPENDS
            ${COMMIT_ID}
        COMMAND
            ${CMAKE_COMMAND} -E echo ${COMMIT_ID} > ./version.md
        COMMENT
            "Generating file version.md"
        VERBATIM)
  1. 但是,如果您指定静态字符串,则项目构建时不会出现错误:
    add_custom_command(TARGET ${APP_NAME} POST_BUILD
        WORKING_DIRECTORY
            $<TARGET_FILE_DIR:${APP_NAME}>
        DEPENDS
            ${COMMIT_ID}
        COMMAND
            ${CMAKE_COMMAND} -E echo "COMMIT_ID" > ./version.md
        COMMENT
            "Generating file version.md"
        VERBATIM)

使用 ${COMMIT_ID} 变量的问题在于它可能包含 尾随空格或换行符 从它在 execute_process 中创建时起。您可以添加 OUTPUT_STRIP_TRAILING_WHITESPACE 参数以在 execute_process 的输出被用于变量之前清理它:

execute_process(COMMAND git rev-parse HEAD
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    OUTPUT_VARIABLE COMMIT_ID
    OUTPUT_STRIP_TRAILING_WHITESPACE
)