[問題] 前定義如何轉為字串?

看板C_and_CPP (C/C++)作者 (心動)時間10年前 (2015/10/06 17:09), 10年前編輯推噓1(108)
留言9則, 2人參與, 最新討論串1/1
開發平台(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

10/06 17:53, , 1F
用 #REG 定義一個新 macro,詳細→ https://gcc.gnu.org/on
10/06 17:53, 1F

10/06 17:53, , 2F
linedocs/cpp/Stringification.html
10/06 17:53, 2F
修改如下 #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

10/06 19:00, , 3F
gcc -DREG=\"US\" hello.c -o hello
10/06 19:00, 3F

10/06 19:19, , 4F
若確實要使用 gcc -DREG=US ... 的方式, 那 C 就要改成
10/06 19:19, 4F

10/06 19:19, , 5F
#define STR(X) #X
10/06 19:19, 5F

10/06 19:19, , 6F
#define S(X) STR(X)
10/06 19:19, 6F

10/06 19:20, , 7F
printf("%s\n", S(REG));
10/06 19:20, 7F

10/06 19:21, , 8F
這樣 S(REG) 才會轉成 "US"
10/06 19:21, 8F

10/06 19:42, , 9F
上面這段跟 #1Lxg5IxJ (C_and_CPP) 所提方式一樣道理.
10/06 19:42, 9F
文章代碼(AID): #1M4u-z0a (C_and_CPP)
文章代碼(AID): #1M4u-z0a (C_and_CPP)