70

我正在使用 GNU-make Makefile 构建具有多个目标( 、 和一些项目特定目标)的 Call项目clean。在调试过程中,我想在不永久编辑 Makefile 的情况下将一些标志附加到单个构建(例如添加调试符号或设置预处理器标志)。

过去,我是按如下方式完成的(使用调试符号示例):

make target CFLAGS+=-g

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

4

4 回答 4

92

查看覆盖指令。您可能需要修改一次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 
于 2010-01-24T23:37:42.283 回答
31

作为记录,从命令行的角度来看,@Carl Norum 的答案预先添加变量。

我需要一种方法来实际追加并提出:

override CFLAGS := -Wall $(CFLAGS)
于 2012-02-27T12:47:22.307 回答
23

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

  • 使用命令行参数:

    make VAR=value
    
  • 使用环境:

    export VAR=var; make
    

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

    VAR=var make
    

它们略有不同。第一个更强。这意味着你知道你想要什么。第二个可能被认为是一个提示。它们之间的区别在于运算符=+=(没有override)。这些运算符在命令行中定义变量时会被忽略,但在环境中定义变量时不会被忽略。因此,我建议你有一个 Makefile :

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

并调用它:

CFLAGS=-g make

注意,如果你想提现-Wall,你可以使用:

make CFLAGS=

请不要使用override关键字,否则您将无法更改受override.

于 2015-09-21T13:26:09.977 回答
7

只是一个注释,因为我很困惑 - 让它成为文件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过一次,它只能附加另一个语句 with override(正常的赋值将被忽略);
  • 当根本没有override的时候;尝试+=从命令行追加(如 中)会覆盖该变量的每个实例。
于 2013-04-17T04:06:12.597 回答