Issue
I want to use cmake execute_process, or similar, to get the git hash at build time not at configure time. I have it working and populating the git hash at configure time, but I would like to have it update at build time.
Here is an example of what I have to get the git hash at configure time.
(this is an example from Profession Cmake https://crascit.com/professional-cmake/)
foobar_version.cpp.in
std::string getFooBarGitHash()
{
return "@FooBar_GIT_HASH@";
}
CMakeLists.txt
find_package(Git REQUIRED)
execute_process(
COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
RESULT_VARIABLE result
OUTPUT_VARIABLE FooBar_GIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(result)
message(FATAL_ERROR "Failed to get git hash: ${result}")
endif()
configure_file(foobar_version.cpp.in foobar_version.cpp @ONLY)
This works and populates a foobar_version.cpp file with the git hash as expected, but I want to have this run at build time. Is there a convenient way to do this?
Solution
I solved this problem by generating a custom version.h header file with a python script GitHashExtractor and the following snippet in my cmake file.
set(PROJECT_SOURCES
[... your files ...]
GitHashExtractor/firmwareVersion.py
GitHashExtractor/version.h
)
# START github.com/ni-m/gitHashExtractor
set(VERSION_FILE "./GitHashExtractor/version.h")
set(VERSION_PYTHON "./GitHashExtractor/firmwareVersion.py")
set_property(SOURCE ${VERSION_FILE} PROPERTY SKIP_AUTOGEN ON) #Qt Framework
add_custom_command(OUTPUT ${VERSION_FILE}
COMMAND python ${VERSION_PYTHON} [ARGS] [Qt.h]
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMENT "Creating ${VERSION_FILE}"
)
# target GitHashExtractor is always built
add_custom_target(GitHashExtractor ALL DEPENDS ${VERSION_FILE})
# END github.com/ni-m/gitHashExtractor
The last line makes sure to always build this target.
This snipped is tested unter the Qt framework with cmake. You may want to remove the set_property(SOURCE ${VERSION_FILE} PROPERTY SKIP_AUTOGEN ON)
line if you're not using Qt.
Answered By - Marco Answer Checked By - Mary Flores (WPSolving Volunteer)