文章目录
1、个人方法
1.1 获取commit-id
采用git log
获取代码commit-id字符串,记为version_str
1.2 makefile定义宏
如定义1个名为VERSION
的自定义宏,然后将version_str
值赋给该宏
1.3 代码改动
在代码内利用makefile内定义的宏VERSION
;
#ifdef VERSION
...
#endif
1.4 范例
/*----------------makefile---------------*/
CC=g++
CFLAGS+=-D VERSION=\"XXX\"
tt:main.cpp
$(CC) $(CFLAGS) $^ -o $@
%.o:%.cpp
$(CC) $(CFLAGS) -c %<
PHONY:clean
clean:
rm -rf *.o tt
注意:宏
VERSION=\"XXX\"
,输出字符串XXX
;
/*----------------mainc.cpp---------------*/
#include <iostream>
using namespace std;
int main()
{
//
#ifdef VERSION
cout<<"++++++++++++++++++++++"<<endl;
cout<<VERSION<<endl;
#endif
return 1;
}
2、别人方法
2.1 CMake获取git commit-Id
- CMakeLists.txt
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})
- main.cpp
#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;
}
- 效果
2.2 Makefile 获取git commit-ID
- Makefile
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
- main.cpp
#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;
}
- main.c
#include <stdio.h>
int main()
{
printf("GitPath[%s],GitVersion[%s],BuildTime[%s%s]\n",GIT_PATH,GIT_VERSION,__DATE__,__TIME__);
return 0;
}