C语言宏展开异常:显式代码正常但宏调用报成员不存在错误
Why does my C macro call fail with a "no member named 'objScope'" error when the expanded code works?
Your issue stems from a name collision between your macro parameter and a struct member name, which causes the preprocessor to incorrectly replace the struct member identifier during macro expansion.
Let's break down what's happening:
- Your macro defines a second parameter named
scopeType, which exactly matches the name of thescopeTypemember instruct Scope. - When you call
newScope(string, objScope), the C preprocessor replaces every occurrence of the parameter namescopeType(as an independent token) withobjScope—including the struct member name in the line:intrprtr.scope[intrprtr.scope_layer-1].scopeType = (scopeType); - This means your macro actually expands to:
({ intrprtr.scope = realloc(intrprtr.scope, intrprtr.scope_layer*sizeof(struct Scope)); strncpy(intrprtr.scope[intrprtr.scope_layer-1].string, (string), 255); intrprtr.scope[intrprtr.scope_layer-1].objScope = (objScope); }) - Since
struct Scopehas no member namedobjScope(onlyscopeType), the compiler throws the error you see.
In contrast, your manual expanded code uses the correct struct member name scopeType and assigns objScope to it, which is why it works.
Fixes for the Macro
The simplest solution is to rename the macro parameter to avoid the collision:
#define newScope(string, scope_type) ({ \ intrprtr.scope = realloc(intrprtr.scope, intrprtr.scope_layer*sizeof(struct Scope)); \ strncpy(intrprtr.scope[intrprtr.scope_layer-1].string, (string), 255); \ /* Ensure we're accessing the struct member, not the macro parameter */ \ intrprtr.scope[intrprtr.scope_layer-1].scopeType = (scope_type); \ })
Additional Notes
- Be cautious with
reallochere: ifscope_layeris 0, this will behave likefree(intrprtr.scope), which may not be intentional. Ensurescope_layeris at least 1 before calling this macro. strncpydoesn't automatically add a null terminator. If your input string is exactly 255 characters long, thestringarray in your struct will lack a terminator. Add this line afterstrncpyto fix it:intrprtr.scope[intrprtr.scope_layer-1].string[254] = '\0';
内容的提问来源于stack exchange,提问作者Austin
相关产品推荐
相关产品推荐

