通过命令行附加到 GNU make 变量

我使用 GNU-make Makefile 来构建一个具有多个目标(allclean和一些特定于项目的目标)的 C 项目。在调试过程中,我希望在不永久编辑 Makefile 的情况下为单个构建添加一些标志(例如,添加调试符号或设置预处理器标志)。

在过去,我是这样做的(使用调试符号示例) :

make target CFLAGS+=-g

不幸的是,这并没有附加到 CFLAGS变量,而是清除它并停止它的编译。有没有一种干净的方法可以做到这一点,而不需要定义某种附加在 CFLAGSLDFLAGS末尾的虚拟变量?

60911 次浏览

看看 覆盖指令。您可能需要修改 makefile 一次,但它应该可以完成您想要的操作。

Makefile 示例:

override CFLAGS += -Wall


app: main.c
gcc $(CFLAGS) -o app main.c

命令行示例:

$ make
gcc -Wall -o app main.c
$ make CFLAGS=-g
gcc -g -Wall -o app main.c

郑重声明,@Carl Norum 的答案是 假设变量,从命令行的角度来看。

我需要一种方法来实际附加,并得出:

override CFLAGS := -Wall $(CFLAGS)

只是一个说明,因为我感到困惑-让这是文件 testmake:

$(eval $(info A: CFLAGS here is $(CFLAGS)))


override CFLAGS += -B


$(eval $(info B: CFLAGS here is $(CFLAGS)))


CFLAGS += -C


$(eval $(info C: CFLAGS here is $(CFLAGS)))


override CFLAGS += -D


$(eval $(info D: CFLAGS here is $(CFLAGS)))


CFLAGS += -E


$(eval $(info E: CFLAGS here is $(CFLAGS)))

然后:

$ make -f testmake
A: CFLAGS here is
B: CFLAGS here is -B
C: CFLAGS here is -B
D: CFLAGS here is -B -D
E: CFLAGS here is -B -D
make: *** No targets.  Stop.
$ make -f testmake CFLAGS+=-g
A: CFLAGS here is -g
B: CFLAGS here is -g -B
C: CFLAGS here is -g -B
D: CFLAGS here is -g -B -D
E: CFLAGS here is -g -B -D
make: *** No targets.  Stop.

随着 override指令从 testmake文件中删除:

$ make -f testmake
A: CFLAGS here is
B: CFLAGS here is -B
C: CFLAGS here is -B -C
D: CFLAGS here is -B -C -D
E: CFLAGS here is -B -C -D -E
make: *** No targets.  Stop.
$ make -f testmake CFLAGS+=-g
A: CFLAGS here is -g
B: CFLAGS here is -g
C: CFLAGS here is -g
D: CFLAGS here is -g
E: CFLAGS here is -g
make: *** No targets.  Stop.

那么,

  • 如果一个变量使用 override一次,它只能与另一个语句附加 override(正常的赋值将被忽略) ;
  • 当根本不存在 override时; 尝试从命令行追加(如 +=)覆盖该变量的每个实例。

有两种方法可以传递变量:

  • 使用命令行参数:

    make VAR=value
    
  • Using environment:

    export VAR=var; make
    

    或(更好,因为它只改变当前命令的环境)

    VAR=var make
    

They are slightly different. The first one is stronger. It mean you know what you want. The second may be considered like a hint. Difference between them is about operators = and += (without override). These operators are ignored when a variable is defined on command line, but are not ignored when variable is defined in environment. Thus, I suggest you to have a Makefile with:

CC ?= gcc
CFLAGS += -Wall
INTERNAL_VARS = value

然后说:

CFLAGS=-g make

注意,如果要撤回 -Wall,可以使用:

make CFLAGS=

请不要使用 override关键字,否则你将没有任何办法改变一个变量与 override的影响。