2010-01-24 101 views
48

我正在使用GNU make Makefile來構建一個包含多個目標(all,clean和幾個項目特定目標)的C項目。在調試過程中,我想將一些標誌添加到單個版本中,而無需永久編輯Makefile(例如,添加調試符號或設置預處理器標誌)。通過命令行追加到GNU make變量

在過去,我已經做了如下(使用調試符號爲例):

make target CFLAGS+=-g 

不幸的是,這是不附加到CFLAGS變量,而是將其清除,並從編譯停止它。如果沒有在CFLAGSLDFLAGS的末尾添加一些虛擬變量,是否有乾淨的方法呢?

回答

65

查看override directive。你可能需要修改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 
+0

感謝您的參考鏈接。這看起來像是解決問題的更好方案之一。 –

20

對於記錄,@Carl Norum時的回答預規劃變量,命令行透視。

我需要一種方法來實際追加,並想出了:

override CFLAGS := -Wall $(CFLAGS) 
6

剛一說明,我糊塗了 - 讓這個做文件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;試圖從命令行追加(如+=)覆蓋該變量的每個實例。
9

有兩種方式傳遞變量進行:

  • 使用命令行參數:

    make VAR=value 
    
  • 使用環境:

    export VAR=var; make 
    

    或(更好,因爲它只改變現在的指揮官的環境d)

    VAR=var make 
    

他們是略有不同。第一個更強。這意味着你知道你想要什麼。第二個可能被認爲是一個提示。它們之間的區別在於運營商=+=(不含override)。當在命令行中定義變量時忽略這些運算符,但在環境中定義變量時不會忽略這些運算符。因此,我建議你有一個Makefile:

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

,並稱之爲:

CFLAGS=-g make 

注意,如果你想退出-Wall,你可以使用:

make CFLAGS= 

請不要使用override關鍵字,否則您將無法更改受override影響的變量。