Reputation: 2337
I'm trying to read the Git commit hash into a C++ application. Using the following CMakeList file I get the correct commit hash.
CMakelist
FIND_PACKAGE(Git)
IF(GIT_FOUND)
EXECUTE_PROCESS(
COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
OUTPUT_VARIABLE COMMIT
OUTPUT_STRIP_TRAILING_WHITESPACE)
MESSAGE( STATUS "Commit : ${COMMIT}" )
ELSE(GIT_FOUND)
SET(COMMIT 0)
ENDIF(GIT_FOUND)
set(yada "${COMMIT}")
MESSAGE("lkpoopkpoef".${yada})
add_definitions("-D_GIT_COMMIT_HASH=${yada}")
However, when I try to read the value in C++ in the following function, I get an error.
main.cpp
std::string getGitCommit()
{
#ifdef _GIT_COMMIT_HASH
return _GIT_COMMIT_HASH;
#endif
return "unavailable";
}
In function ‘std::__cxx11::string getGitCommit()’: :0:18: error: ‘d2cdfd2’ was not declared in this scope
d2cdfd2 is the commit hash.
I'm referring to
I'm trying to avoid creating another file to store the commit hash and would like to directly read this from the CMakeList.
I'm using catkin_make to build the application on an Ubuntu 16.04
What am I doing wrong here?
Upvotes: 1
Views: 345
Reputation: 63481
The hash is not actually a string. Even the compiler error is telling you this.
You need to use the stringize operator (#
).
From Stringizing operator in C/C++:
#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)
#ifdef _GIT_COMMIT_HASH
return STRINGIFY(_GIT_COMMIT_HASH);
#endif
Note also that since this function always returns a string literal, it may be more appropriate for the return type to be const char*
instead of std::string
. Although it's perfectly valid either way.
One other point is that if the hash is not available, your compiler may warn you that the second return
is unreachable. If you don't want that to happen, then use a #else
directive:
#ifdef _GIT_COMMIT_HASH
return STRINGIFY(_GIT_COMMIT_HASH);
#else
return "unavailable";
#endif
Upvotes: 2