关于如何在make一个Linux下的C/C++工程时,自动添加版本号、编译日期等信息

本篇的目的:在makefile里,将系统当前的时间传递进待编译的C/C++工程中,用以指示编译执行的时间,以及版本信息等。


不多说了,先来看效果:

当前时间:2017.01.20  0:29

编译完成后运行效果:

ubuntu@ubuntu:~/Desktop/ccc$ ./test 
============================
Soft version:V1.01
compile date:2017.01.20  0:29
============================


。。。。。。

过了8分钟后,再次编译运行:

ubuntu@ubuntu:~/Desktop/ccc$ ./build.sh 
rm -f auto_version.h test main.o
Build start...
`touch auto_version.h`
cc    -c -o main.o main.c
gcc main.o auto_version.h -o test
Build OK
ubuntu@ubuntu:~/Desktop/ccc$ 
ubuntu@ubuntu:~/Desktop/ccc$ 
ubuntu@ubuntu:~/Desktop/ccc$ ./test 
============================
Soft version:V1.01
compile date:2017.01.20  0:37
============================

注意时间变化。



下面贴代码:

这就是关于如何make一个Linux下的C/C++工程时,自动添加版本号、编译日期等信息:

//main.c

#include <stdio.h>
#include "auto_version.h"

int main(int argc,char *argv[])
{
#ifdef VER_AUTO
	printf("============================\n");
	printf("Soft version:%s\n",VERSION);
	printf("compile date:%s\n",DATE);
	printf("============================\n");
#else
	printf("============================\n");
	printf("creat by ZhongKunjiang\n");
	printf("mail:[email protected]\n");
	printf("============================\n");
#endif	
	return 0;
}



//Makefile

VERSION_STRING := "V1.01"
DATE_STRING := `date "+20%y.%m.%d %k:%M"`

.PHONY:all
all:test
test:main.o auto_version.h
	gcc $^ -o $@

main.o:main.c auto_version.h

auto_version.h:
	`touch auto_version.h`
	@echo "#define VER_AUTO 1" > auto_version.h                         # > :覆盖文本原来内容
	@echo "#define VERSION \"$(VERSION_STRING)\"" >> auto_version.h     # >> :追加内容到文本末尾
	@echo "#define DATE \"$(DATE_STRING)\""	>> auto_version.h           # >> :追加内容到文本末尾


clean:
	rm -f auto_version.h test main.o



//build.sh

set -e #告诉bash如果任何语句的执行结果不是true则退出


make clean

echo -e "\e[36m""Build start...""\e[m"  # "\e[36m" :设置打印颜色,"\e[m" :清除打印颜色
make all
echo -e "\e[36m""Build OK""\e[m"



接下来,chmod +x build.sh

执行 ./build.sh

编译成功。

运行./test

即可看到如上效果


猜你喜欢

转载自blog.csdn.net/ZHONGkunjia/article/details/54627294