C语言使用宏初始化结构体的问题

来源:互联网 发布:数据库系统基础知识 编辑:程序博客网 时间:2024/05/29 18:36

Linux内核源码中广泛的使用宏来进行结构体对象定义和初始化,但是进行对象初始化的时候需要注意宏参数和结构体成员名冲突的问题,下面进行简单测试说明,编写一个程序创建一个结构体,然后使用宏进行结构体初始化:

  1 #include "stdio.h"  2   3 struct guy  4 {  5         int id;  6         char *name;  7         int age;  8 };  9  10 #define NEW_GUY(id,name,age) \ 11 { \ 12         .id = id, \ 13         .name = name, \ 14         .age = age, \ 15 } 16  17 int main() 18 { 19         struct guy guy1 = NEW_GUY(0,"tangquan",22); 20         printf("%d,%s,%d\r\n",guy1.id,guy1.name,guy1.age); 21         return 0; 22 } 23 

编译后发现错误:

tq@ubuntu:/mnt/hgfs/vmshare$ gcc test.c -o tartest.c: In function ‘main’:test.c:19:28: error: expected identifier before numeric constant  struct guy guy1 = NEW_GUY(0,"tangquan",22);                            ^test.c:12:3: note: in definition of macro ‘NEW_GUY’  .id = id, \   ^test.c:13:2: error: expected ‘}’ before ‘.’ token  .name = name, \  ^test.c:19:20: note: in expansion of macro ‘NEW_GUY’  struct guy guy1 = NEW_GUY(0,"tangquan",22);                    ^tq@ubuntu:/mnt/hgfs/vmshare$ 

单看错误我是真没找到有什么问题,后来发现宏参数名和结构体的成员名相同,我猜想宏展开之后会不会出现奇异,例如12行的“.id = id”会被展开成“.0 = 0”而不是“.id = 0”,所以我将程序的宏修改了一下宏参数:

  1 #include "stdio.h"  2   3 struct guy  4 {  5         int id;  6         char *name;  7         int age;  8 };  9  10 #define NEW_GUY(_id,_name,_age) \ 11 { \ 12         .id = _id, \ 13         .name = _name, \ 14         .age = _age, \ 15 } 16  17 int main() 18 { 19         struct guy guy1 = NEW_GUY(0,"tangquan",22); 20         printf("%d,%s,%d\r\n",guy1.id,guy1.name,guy1.age); 21         return 0; 22 } 23 

修改后编译无错,运行正常,不知道问题是不是我猜想的那样,反正宏参数名和结构体的成员名不要相同就行了。

原创粉丝点击