cmake - 在 CMake 配置时构建程序

标签 cmake

有没有办法让 CMake 在配置时(即当您运行 cmake . 时)构建并运行 C++ 程序,但前提是该程序尚未构建?

例如,假设我有一个程序(用 C++ 编写)可以生成主程序的版本信息,并且我想在主程序的 CMakeLists.txt 中使用该版本信息。

我相信您可以通过让主 CMakeLists.txt 作为子进程执行 cmake 来完成此操作,但这看起来不太干净。有更好的“官方”方式吗?

编辑:This基本上是同一个问题,似乎没有真正好的方法来做到这一点。

最佳答案

我同意以下评论:在这种情况下,解决您的根本问题可能比直接回答您的问题更容易。以下是我如何从 git 获取分支/版本信息并将其放入我的程序中:

我在支持 Windows 和多个 Linux 变体的代码库上使用此方法。

创建一个 CMake 宏以从 git 中提取信息:

# Get the current Git commit hash
macro(git_information BRANCH_VAR COMMIT_VAR COMMIT_VAR_SHORT)

    # Get the branch name
    execute_process(
    COMMAND git rev-parse --abbrev-ref HEAD
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    OUTPUT_VARIABLE ${BRANCH_VAR}
    OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    MESSAGE(STATUS "GIT: Current branch -> ${${BRANCH_VAR}}")

    # Retrigger configuration process each time config file changes
    get_filename_component(_cfg_name "${CMAKE_SOURCE_DIR}/.git/refs/heads/${BRANCH}" NAME)
    configure_file("${CMAKE_SOURCE_DIR}/.git/refs/heads/${BRANCH}" "${_cfg_name}.tmp")
    set_source_files_properties(${_cfg_name}.tmp PROPERTIES GENERATED true)

    # Get the head commit
    execute_process(
    COMMAND git rev-parse HEAD
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    OUTPUT_VARIABLE ${COMMIT_VAR}
    OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    MESSAGE(STATUS "GIT: Current commit -> ${${COMMIT_VAR}}")

    # Get the short version of the head commit
    execute_process(
    COMMAND git rev-parse --short HEAD
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    OUTPUT_VARIABLE ${COMMIT_VAR_SHORT}
    OUTPUT_STRIP_TRAILING_WHITESPACE
    )

endmacro()

然后在顶级 CMakeLists.txt 中像这样调用宏:

find_package(Git)
if(GIT_FOUND)
    git_information(BRANCH GIT_COMMIT GIT_COMMIT_SHORT)
ELSE()
    # as a fallback, use the directory name as the branch name
    GET_FILENAME_COMPONENT(BRANCH ${CMAKE_CURRENT_SOURCE_DIR} NAME)
ENDIF()

为了真正将信息输入到程序中,我使用 configure_file(如果您不熟悉,请参阅 documentation):

configure_file(include/version.h.in version.h @ONLY NEWLINE_STYLE LF)

该文件看起来像这样:

#include <string>

namespace myProg
{
    static const std::string BRANCH("@BRANCH@");
    static const std::string GIT_COMMIT("@GIT_COMMIT@");
    static const std::string GIT_COMMIT_SHORT("@GIT_COMMIT_SHORT@");
}

您可以想象,通过使用适当的 git 命令添加额外的 execute_process block ,该宏也可用于从 git 中提取标签或描述信息。

关于cmake - 在 CMake 配置时构建程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41876226/

相关文章:

curl - libCurl x64 构建问题 Visual Studio 2013 (x64) Visual Studio & CMake

c++ - CMake:如何检查是否已定义某些标志

c++ - Qt5 和 Cmake 链接 QApplication 头错误

c++ - Eclipse 中的 Cmake 支持

c++ - 在 CMake 阶段而不是构建阶段构建和运行 C++ 代码

opencv - 为 python3 安装 opencv

batch-file - 如何从CMake运行.bat文件?

ubuntu 17.04 cmake x265

c++ - MSVC C++ 调用 GFortran 子例程

C++ 链接器找不到函数声明( undefined reference )