简体   繁体   中英

Error reading the Git commit hash into C++

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

  1. http://xit0.org/2013/04/cmake-use-git-branch-and-commit-details-in-project/
  2. How to read a CMake Variable in C++ source code

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM