0

When using cmake, we wish for our distibutable files to contain some information about the release itself (such as a git tag or commit point). This is so we can basically tell from the installed package alone what release it is.

In other words, we're looking for something like the output of git show | head -1:

commit 695ec2ceca0854...blahblahblah

Our cmake files are fairly simple, consisting of:

add_executable(exename main.cpp functions.cpp functions.h)

How do we configure CMakeLists.txt to both generate this information and include it in the packaging for the project.

This could be baked in to the executable as a file with one string object like:

char *x = "XYZZY-commit 695ec2ceca0854...blahblahblah";

so that we can run strings on the executable to get the information.

It could also be a totally separate file like commitpoint.txt which is packaged and shipped with the executable.

Or, if anyone has a better way of doing this, I'm open to suggestions.

What I'd prefer to avoid is something that requires manual intervention when building, such as maintaining a module with the information hard-coded into it and stored in git itself. I'm looking for something that's fully automated.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • https://github.com/llvm-mirror/llvm/blob/master/cmake/modules/GenerateVersionFromCVS.cmake ? – arrowd Jun 13 '18 at 08:35

1 Answers1

1

Cmake ships with a find module for git that can be used like this

find_package(Git)

if(Git_FOUND)
    execute_process(COMMAND "${GIT_EXECUTABLE}" log --pretty=format:%h -n 1
        WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
        OUTPUT_VARIABLE commit_sha1
        ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
else()
    set(commit_sha1 "Unknown")
endif()

where git arguments and the working directory could obviously be adjusted to your needs. The variable storing the desired info can now be used when configuring a file,

configure_file(version.cpp.in version.cpp)

where version.cpp.in contains

const char *gitInfo = "@commit_sha1@";

The generated version.cpp will be created in the build directory, and is included into the executable by

add_executable(exename ... ${CMAKE_CURRENT_BINARY_DIR}/version.cpp)
lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 1
    `configure_file` works at configuration time. A git pull could change the commit without requiring CMake to rerun. `add_custom_command` and/or `add_custom_target` with the found Git executable might work better. – John Jun 13 '18 at 12:42
  • Good point! I found [this](https://stackoverflow.com/q/3780667) question on the identical problem with svn repository info, where a solution for generating this info at build time is proposed. – lubgr Jun 13 '18 at 19:59