我希望能够在我的代码中使用 git 版本的变量。如果我使用 make
设置变量,然后在 .h
文件中覆盖它,则打印的最终值将来自“.h”文件。有没有办法覆盖 makefile 中的 .h
?
executing make
gcc -O2 -pipe -pedantic -std=c99 -Wall -O3 -ledit -DVERSION=\"\" -c main.c -o main.o
In file included from main.c:9:0:
openshell.h:17:0: warning: "VERSION" redefined [enabled by default]
#define VERSION "v0.1a"
我正在尝试从 github 设置变量 VERSION
以便可以查看版本:
$ ./a.out --version
OpenShell version 0.1(a)
Version: v0.1a-2-gc6b1-dirty
我有这个 makefile
CC = gcc
GIT_VERSION := $(shell git describe --abbrev=4 --dirty --always --tags)
CFLAGS := $(CFLAGS) -pedantic -std=c99 -Wall -O3 -ledit -g -DVERSION=\"$(GIT_VERSION)\"
shell: main.o
$(CC) -o shell main.o errors.c util.c pipeline.c -ledit
main.o: main.c errors.c util.c
.PHONY: clean
clean:
rm -f *.o
然后它可以在 Linux Ubuntu 上运行,但不能在 BSD 上运行,对于 PC-BSD,变量不会显示:
dac:/usr/home/dac/openshell $ make
The Command is: make
27152: executing make
gcc -O2 -pipe -pedantic -std=c99 -Wall -O3 -ledit -DVERSION=\"\" -c main.c -o main.o
main.c: In function 'trimstring':
main.c:116:9: warning: value computed is not used [-Wunused-value]
*tmp++;
^
main.c:119:17: warning: comparison between pointer and integer [enabled by default]
while (*tmp != NULL) {
^
main.c: In function 'exec_program':
main.c:444:9: warning: implicit declaration of function 'snprintf' [-Wimplicit-function-declaration]
snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));
^
main.c:444:9: warning: incompatible implicit declaration of built-in function 'snprintf' [enabled by default]
gcc -o shell main.o errors.c util.c pipeline.c -ledit
dac:/usr/home/dac/openshell $ ./shell --version
The Command is: ./shell --version
27181: executing ./shell
OpenShell version 0.1(a)
Version:
dac:/usr/home/dac/openshell $
更新 160426 07:49 CET
现在它可以在 Ubuntu 上使用(但删除 .h 文件中的旧版本号可能很危险) `GIT:= $(shell head -n -1 openshell.h > temp.txt ; mv temp.txt openshell.h ;git 描述 --abbrev=4 --dirty --always --tags > VERSION; echo "#define VERSION\"$(GIT_VERSION)\"">> openshell.h)
更新后的 Makefile 现在是:
CC = gcc
GIT_VERSION := $(shell git describe --abbrev=4 --dirty --always --tags)
CFLAGS := $(CFLAGS) -L/usr/local/include/ -L/usr/include -pedantic -std=c99 -Wall -O3 -g -DVERSION=\"$(GIT_VERSION)\" -ledit -lncurses
LDIRS = -L/usr/local/lib -L/usr/lib
LIBS = -ledit lncurses -lcurses
shell: main.o
$(CC) -o shell main.o errors.c util.c pipeline.c -ledit -lncurses -lcurses
main.o: main.c errors.c util.c
USERNAME := $(shell whoami >> username.txt)
GIT:= $(shell head -n -1 openshell.h > temp.txt ; mv temp.txt openshell.h;git describe --abbrev=4 --dirty --always --tags > VERSION; echo "\#define VERSION \"$(GIT_VERSION)\"" >> openshell.h)
.PHONY: clean
clean:
rm -f *.o
`
最佳答案
为了避免警告:“VERSION”重新定义
,请用#ifndef 包装#define:
#ifndef VERSION
#define VERSION "v0.1a"
#endif
关于c - 如何让我的程序使用 BSD 打印其 github 版本号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36813687/