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

来源:互联网 发布:2016年网络流行语大全 编辑:程序博客网 时间:2024/05/22 05:12

本篇的目的:在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_AUTOprintf("============================\n");printf("Soft version:%s\n",VERSION);printf("compile date:%s\n",DATE);printf("============================\n");#elseprintf("============================\n");printf("creat by ZhongKunjiang\n");printf("mail:zhongkunjiang@hotmail.com\n");printf("============================\n");#endifreturn 0;}



//Makefile

VERSION_STRING := "V1.01"DATE_STRING := `date "+20%y.%m.%d %k:%M"`.PHONY:allall:testtest:main.o auto_version.hgcc $^ -o $@main.o:main.c auto_version.hauto_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 cleanecho -e "\e[36m""Build start...""\e[m"  # "\e[36m" :设置打印颜色,"\e[m" :清除打印颜色make allecho -e "\e[36m""Build OK""\e[m"



接下来,chmod +x build.sh

执行 ./build.sh

编译成功。

运行./test

即可看到如上效果


0 0