看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) gcc 問題(Question): 在 make 時傳入 REG如下 make REG=US 在 makefile中加入 CFLAGS += -DREG=$(REG) 之後gcc大概會變成 gcc -DREG=US hello.c -o hello 想在程式中印出REG printf("%s\n", REG); 這樣會顯示為錯誤, US無定義 請教如何讓 REG變成 "US" ? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.249.108.83 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1444122557.A.024.html ※ 編輯: ck49 (111.249.108.83), 10/06/2015 17:09:43
WanCW: 用 #REG 定義一個新 macro,詳細→ https://gcc.gnu.org/on 10/06 17:53
WanCW: linedocs/cpp/Stringification.html 10/06 17:53
修改如下 #include <stdio.h> #include <stdlib.h> #define EXP US #define WARN_IF(EXP) \ do { if (EXP) \ fprintf (stderr, "Warning: " #EXP "\n"); } \ while (0) int main(void) { WARN_IF(EXP); return EXIT_SUCCESS; } 結果 gcc test.c -o test test.c: In function ??main??: test.c:15: error: ??US?? undeclared (first use in this function) test.c:15: error: (Each undeclared identifier is reported only once test.c:15: error: for each function it appears in.) 請教有什麼地方需要更改? 感恩 ※ 編輯: ck49 (111.249.108.83), 10/06/2015 18:54:50
yvb: gcc -DREG=\"US\" hello.c -o hello 10/06 19:00
yvb: 若確實要使用 gcc -DREG=US ... 的方式, 那 C 就要改成 10/06 19:19
yvb: #define STR(X) #X 10/06 19:19
yvb: #define S(X) STR(X) 10/06 19:19
yvb: printf("%s\n", S(REG)); 10/06 19:20
yvb: 這樣 S(REG) 才會轉成 "US" 10/06 19:21
yvb: 上面這段跟 #1Lxg5IxJ (C_and_CPP) 所提方式一樣道理. 10/06 19:42