8

I would like to write output of git describe as a string to a file, so I can embed the information in my binary (C++). This has to work across platforms.

The best I can yet come up with was:

add_custom_target( SubmarineGitVersion
    COMMAND cmd /c "${CMAKE_EXECUTABLE}" echo czstring GIT_VERSION = STRINGIFY\( > "${CMAKE_CURRENT_BINARY_DIR}/GitVersion.hpp"
    COMMAND cmd /c "${GIT_EXECUTABLE}" describe --tags --always >> "${CMAKE_CURRENT_BINARY_DIR}/GitVersion.hpp"
    COMMAND cmd /c "${CMAKE_EXECUTABLE}" echo \) >> "${CMAKE_CURRENT_BINARY_DIR}/GitVersion.hpp"
)

This roughly works on Windows (is missing a ; at the end):

czstring GIT_VERSION = STRINGIFY(
tag-343434
)

Is there any better/more cross-platform way of doing this?

1 Answer 1

10

Common way for create "version" files is using configure_file command. Such way file will be created at configure stage:

GitVersion.hpp.in:

czstring GIT_VERSION = STRINGIFY(
${GIT_REPO_VERSION}
)

CMakeLists.txt:

# Store version into variable
execute_process(COMMAND ${GIT_EXECUTABLE} describe --tags --always
    OUTPUT_VARIABLE GIT_REPO_VERSION)
# The variable will be used when file is configured
configure_file("GitVersion.hpp.in" "GitVersion.hpp")

If you want to create version file on build stage, move above cmake commands into some file, and execute this file in CMake script mode:

generate_version.cmake:

# Git executable is extracted from parameters.
execute_process(COMMAND ${GIT_EXECUTABLE} describe --tags --always
    OUTPUT_VARIABLE GIT_REPO_VERSION)
# Input and output files are extracted from parameters.
configure_file(${INPUT_FILE} ${OUTPUT_FILE})

CMakeLists.txt:

add_custom_target( SubmarineGitVersion
    COMMAND ${CMAKE_COMMAND}
        -D GIT_EXECUTABLE=${GIT_EXECUTABLE}
        -D INPUT_FILE=${CMAKE_CURRENT_SOURCE_DIR}/GitVersion.hpp.in
        -D OUTPUT_FILE=${CMAKE_CURRENT_BINARY_DIR}/GitVersion.hpp
        -P ${CMAKE_CURRENT_SOURCE_DIR}/generate_version.cmake
)
Sign up to request clarification or add additional context in comments.

1 Comment

I had to add add_dependencies(${EXE} SubmarineGitVersion) in order to make my project automatically make GitVersion.hpp when building. Even then, it only works on a force build because the project doesn't detect that any files are dirty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.