简体   繁体   English

将Git提交哈希读取到C ++中时出错

[英]Error reading the Git commit hash into C++

I'm trying to read the Git commit hash into a C++ application. 我正在尝试将Git提交哈希读取到C ++应用程序中。 Using the following CMakeList file I get the correct commit hash. 使用以下CMakeList文件,我得到正确的提交哈希。

CMakelist 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. 但是,当我尝试通过以下函数在C ++中读取值时,出现错误。

main.cpp 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 在函数'std :: __ cxx11 :: string getGitCommit()'中:: 0:18:错误:未在此范围内声明'd2cdfd2'

d2cdfd2 is the commit hash. d2cdfd2是提交哈希。

I'm referring to 我指的是

  1. http://xit0.org/2013/04/cmake-use-git-branch-and-commit-details-in-project/ 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 如何在C ++源代码中读取CMake变量

I'm trying to avoid creating another file to store the commit hash and would like to directly read this from the CMakeList. 我试图避免创建另一个文件来存储提交哈希,并想直接从CMakeList中读取它。

I'm using catkin_make to build the application on an Ubuntu 16.04 我正在使用catkin_make在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++ : C / C ++中的Stringizing运算符

#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 . 还请注意,由于此函数始终返回字符串文字,因此将返回类型设置为const char*而不是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. 还有一点是,如果散列不可用,则编译器可能会警告您第二个return值不可访问。 If you don't want that to happen, then use a #else directive: 如果您不希望发生这种情况,请使用#else指令:

#ifdef _GIT_COMMIT_HASH
return STRINGIFY(_GIT_COMMIT_HASH);
#else
return "unavailable";
#endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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