CMake获取git commitId
cmake_minimum_required(VERSION 2.8)
project(test)
set(SRCS main.cpp)
# 执行git命令,并把结果重定向到自定义变量(此处是我的变量<GIT_VERSION>)。
execute_process(
COMMAND git log -1 --format=%H //git 命令
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_VERSION
)
execute_process(
COMMAND git remote -v //git 命令
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_REMOTE_PATH
)
# 对得到的结果进行处理,尤其注意 \n,\t,\r之类的特殊字符,在cmake时没问题,但是生成的.cmake文件有问题,导致make出错。
string (REGEX REPLACE ".*\t| .*" "" GIT_PATH ${GIT_REMOTE_PATH})
string (REGEX REPLACE "[\n\t\r]" "" GIT_VERSION ${GIT_VERSION})
# 增加编译选项,把宏导入源码
add_definitions( -DGIT_VERSION=\"${GIT_VERSION}\")
add_definitions( -DGIT_PATH=\"${GIT_PATH}\")
add_executable(app ${SRCS})
#include <iostream>
using namespace std;
int main(){
cout << "Hello world\n";
cout << "[GitPath] " << GIT_PATH << endl; //使用CMakeLists.txt中定义的变量,详情请看该文最下方。
cout << "[GitVersion] " << GIT_VERSION << endl;
cout << "[BuildDate] " << __DATE__ << endl;
cout << "[BuildTime] " << __TIME__ << endl;
return 0;
}
- 效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/82e03d5053653a87fa7595897e89ea4b.png)
- Macro
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/578cca6b72ba3fe0059a707274c0fd78.png)
可以看到,在传入源码后变成了最普通的define宏定义。
Makefile 获取git commitID
TARGET := test
CPP_SRCS += main.cpp
C_SRCS = main.c
CC := g++
C = gcc
#获取GIT版本信息和路径(在代码中使用宏GIT_VERSION和GIT_PATH)
GIT_SHA = $(shell git rev-list HEAD | awk 'NR==1')
GIT_SEQ = $(shell git rev-list HEAD | wc -l)
GIT_VER_INFO = $(GIT_SHA)-$(GIT_SEQ)
GIT_SVR_PATH = $(shell git remote -v | awk 'NR==1' | sed 's/[()]//g' | sed 's/\t/ /g' |cut -d " " -f2)
##定义GIT版本信息宏和路径宏,CFLAGS是编译选项变量
ifneq ($(GIT_VER_INFO),)
CFLAGS += -DGIT_VERSION=\"$(GIT_VER_INFO)\"
else
CFLAGS += -DGIT_VERSION=\"unknown\"
endif
CFLAGS += -DGIT_PATH=\"$(GIT_SVR_PATH)\"
debug :
@echo $(CFLAGS)
m_cpp : $(CPP_SRCS)
$(CC) $(CFLAGS) -o $@ $^
m_c : $(C_SRCS)
$(C) $(CFLAGS) -o $@ $^
clean :
rm m_cpp m_c test main
#include <iostream>
using namespace std;
int main(){
cout << "Hello world\n";
cout << "[GitPath] " << GIT_PATH << endl;
cout << "[GitVersion] " << GIT_VERSION << endl;
cout << "[BuildDate] " << __DATE__ << endl;
cout << "[BuildTime] " << __TIME__ << endl;
cout << "End\n";
return 0;
}
#include <stdio.h>
int main()
{
printf("GitPath[%s],GitVersion[%s],BuildTime[%s%s]\n",GIT_PATH,GIT_VERSION,__DATE__,__TIME__);
return 0;
}