Chinaunix首页 | 论坛 | 博客
  • 博客访问: 199454
  • 博文数量: 65
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 91
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-10 09:41
文章分类
文章存档

2020年(1)

2018年(1)

2017年(30)

2016年(30)

2015年(3)

我的朋友

分类: LINUX

2017-01-06 09:36:58

  1.    在看linux内核代码时会看到某些结构体的定义中包含宏定义:

    点击(此处)折叠或打开

    1. struct i2c_msg {
    2.     __u16 addr;    /* slave address            */
    3.     __u16 flags;
    4. #define I2C_M_TEN        0x0010    /* this is a ten bit chip address */
    5. #define I2C_M_RD        0x0001    /* read data, from slave to master */
    6. #define I2C_M_NOSTART        0x4000    /* if I2C_FUNC_PROTOCOL_MANGLING */
    7. #define I2C_M_REV_DIR_ADDR    0x2000    /* if I2C_FUNC_PROTOCOL_MANGLING */
    8. #define I2C_M_IGNORE_NAK    0x1000    /* if I2C_FUNC_PROTOCOL_MANGLING */
    9. #define I2C_M_NO_RD_ACK        0x0800    /* if I2C_FUNC_PROTOCOL_MANGLING */
    10. #define I2C_M_RECV_LEN        0x0400    /* length will be first received byte */
    11.     __u16 len;        /* msg length                */
    12.     __u8 *buf;        /* pointer to msg data            */
    13. };
    第一次看到觉得怪怪的,虽然我知道宏定义作用于开始定义处,结束于#undef。网上也看到一些人的疑问,比如:

             a) 如果去定义这样的结构体变量,会不会导致一个宏重复定义。

             b) 既然这样没错误,那么有什么好处。

2.    通过看如下程序预编译后的结果:

点击(此处)折叠或打开

  1. struct mystr {
  2.         #define XPOS 1
  3.         #define YPOS 2
  4.         int a;
  5.         char b;
  6. };

  7. int main(void)
  8. {
  9.         struct mystr ex1 = {2, 'a'};
  10.         struct mystr ex2 = {3, 'b'};
  11.         ex1.a=XPOS;
  12.         ex2.a=YPOS;
  13.         
  14.         return 0;
  15. }
gcc main.c -E > main.E预编译后:

点击(此处)折叠或打开

  1. # 1 "main.c"
  2. # 1 ""
  3. # 1 ""
  4. # 1 "main.c"


  5. struct mystr {


  6.  int a;
  7.  char b;
  8. };

  9. int main(void)
  10. {
  11.  struct mystr ex1 = {2, 'a'};
  12.  struct mystr ex2 = {3, 'b'};
  13.  ex1.a=1;
  14.  ex2.a=2;
  15.         
  16.         
  17.        
  18.  return 0;
  19. }

      由此可见,我和存在上述2点疑问的人都忘记预编译和编译的作用时间不同。预编译时,宏被展开,宏定义处被拿掉了,所以接下来再用struct mystr来定义变量时,里面的宏已经不存在了,所以并不会导致一个宏重复被定义。至于这样编写代码的好处,有人说是增加代码的可阅读性,让人知道这些宏只会用于这个结构体中,还有就是便于对这个结构体进行扩展。
阅读(1275) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~