2017-01-03 32 views
1

是否可以用Makefile中的另一個值覆蓋宏?從Makefile覆蓋宏常量

可以說我有一個文件a.c和一個Makefile

a.c文件中,我聲明一個宏爲#define DEBUG 1。 我想通過該值將其從Makefile替換爲CCFLAGS += -D DEBUG -Dvar=1。但是,如果我這樣做,我會得到一個重新定義警告,並且該值保留在a.c中使用的值。

這可能嗎?還有,這是不好的做法?

回答

3

您需要修改您的宏定義本身:

#ifndef DEBUG 
# define DEBUG 1 
#endif 

或者只是完全刪除的定義,並始終通過從構建系統的價值。

2

這可能嗎?

它應通過標記是不可能像-DFOO=bar作爲宏定義的命令行來那些在源代碼文件之前,因此將被覆蓋(重新定義)。

但是,如果您打算通過編譯器標誌控制宏值,您可能會發現ifndef指令有幫助。例如:

[[email protected] tmp]$ cat a.c 
#ifndef TEST 
# define TEST 1 
#endif 

TEST 
[[email protected] tmp]$ cpp a.c 
# 1 "a.c" 
# 1 "<built-in>" 
# 1 "<command-line>" 
# 31 "<command-line>" 
# 1 "/usr/include/stdc-predef.h" 1 3 4 
# 32 "<command-line>" 2 
# 1 "a.c" 




1 
[[email protected] tmp]$ cpp a.c -DTEST=2 
# 1 "a.c" 
# 1 "<built-in>" 
# 1 "<command-line>" 
# 1 "/usr/include/stdc-predef.h" 1 3 4 
# 1 "<command-line>" 2 
# 1 "a.c" 




2