我想要宏,它會在呼叫時將 undefine 常量傳遞給它。像這樣的東西:
#define CONSTANT1 123
#define macro(const) \
#ifdef const \
const \
#undef const \
#else \
#error "constant already used once" \
#endif
int main(){
int a = macro(CONSTANT1); // a = 123
int b = macro(CONSTANT1); // <- preprocessor error "constant already used once"
return 0;
}
可以使用前處理器存檔此功能嗎?
uj5u.com熱心網友回復:
我認為用標準的 C 前處理器是不可能的,但可以用 GCC/CLANG 編譯指示來實作,例如push_macro/pop_macro:
// define a macro that will generate error on expansion
#define CONSTANT1 _Pragma("GCC error \"CONSTANT1 expanded more than once\"")
// save this macro and undefine it
#pragma push_macro("CONSTANT1")
#undef CONSTANT1
// let CONSTANT1 expand to 123, but replace with
// previous error-generation macro
#define CONSTANT1 123 _Pragma("pop_macro(\"CONSTANT1\")")
int a = CONSTANT1;
int b = CONSTANT1;
編譯gcc/clang產生:
prog.c:8:11: error: CONSTANT1 expanded more than once
8 | int b = CONSTANT1;
請注意,編譯指示push_macro/pop_macro是非常可移植的,它們受 GCC、CLANG、MSVS 和英特爾 C 編譯器的支持。
一個更便攜的失敗版本CONSTANT1可能是:
#define CONSTANT1 sizeof(struct {_Static_assert(0, "CONSTANT1 expanded more than once"); int x; })
它需要 C11 兼容的編譯器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324787.html
上一篇:命令列引數值檢查和退出代碼
