前言:
今天遇到一个问题,在makefile中定义个宏,宏为一个字符串,希望将该字符串传递给代码。但是一直传递不过去,最后才找到原因,这里小结一下。
直接上代码,makefile 如下:
1 C_FLAGS := -DTEST_MACRO_HEHE="abcd1234" 2 3 test: test.o 4 gcc -o $@ $^ 5 6 test.o: test.c 7 gcc $(C_FLAGS) -c -o $@ $< -Iinclude 8 9 clean: 10 rm -f *.o 11 rm -f test
makefile 希望将宏TEST_MACRO_HEHE传递到代码中。
来看下代码:
1 #include <stdio.h> 2 3 4 int main() { 5 printf("---- main.\n"); 6 7 #ifdef TEST_MACRO_HEHE 8 printf("==== TEST_MACRO_HEHE %s\n", TEST_MACRO_HEHE); 9 #else 10 printf("==== not defined\n"); 11 #endif 12 13 return 0; 14 }
编译的时候报错:
1 gcc -DTEST_MACRO_HEHE="abcd1234" -c -o test.o test.c -Iinclude 2 test.c: In function ‘main’: 3 <command-line>:0:17: error: ‘abcd1234’ undeclared (first use in this function) 4 test.c:8:41: note: in expansion of macro ‘TEST_MACRO_HEHE’ 5 printf("==== TEST_MACRO_HEHE %s\n", TEST_MACRO_HEHE); 6 ^ 7 <command-line>:0:17: note: each undeclared identifier is reported only once for each function it appears in 8 test.c:8:41: note: in expansion of macro ‘TEST_MACRO_HEHE’ 9 printf("==== TEST_MACRO_HEHE %s\n", TEST_MACRO_HEHE); 10 ^ 11 Makefile:7: recipe for target 'test.o' failed 12 make: *** [test.o] Error 1
如果宏定义为一个数字,例如12,这样编译是可以的,代码中也能识别该宏。
但是,如果想要传递字符串,在Makefile中需要注意,需要使用转义,如下:
1 C_FLAGS := -DTEST_MACRO_HEHE=\"abcd1234\" 2 test: test.o 3 gcc -o $@ $^ 4 test.o: test.c 5 gcc $(C_FLAGS) -c -o $@ $< -Iinclude 6 clean: 7 rm -f *.o 8 rm -f test
转自:https://blog.csdn.net/shift_wwx/article/details/90673865
标签:MACRO,makefile,传递,TEST,源码,printf,test,HEHE From: https://www.cnblogs.com/peifx/p/16947573.html