为啥变量没初始化就用了?那是宏定义啊!,


一、问题

为啥内核有的变量没有初始化就敢直接使用?

二、分析

看上图,其中的5747行的变量nid的确没有定义,就直接使用了,这么做没有问题吗?

其实大家仔细看一下,5765行是一个宏,

到内核源码去找该宏的定义:linux-3.14\include\linux\Nodemask.h

  1. #define for_each_online_node(node) for_each_node_state(node, N_ONLINE) 

其中的for_each_node_state又是一个宏, 继续跟踪该宏,有两处定义

  1. 408 #if MAX_NUMNODES > 1 
  2. …… 
  3. 429 #define for_each_node_state(__node, __state) \ 
  4. 430  for_each_node_mask((__node), node_states[__state]) 
  5. …… 
  6. 450 #else  
  7. …… 
  8. 470 #define for_each_node_state(node, __state) \ 
  9. 471  for ( (node) = 0; (node) == 0; (node) = 1) 
  10. …… 
  11. 481 #endif 

究竟是哪一个定义,由条件#if MAX_NUMNODES > 1 来决定,

  1. #ifdef CONFIG_NODES_SHIFT 
  2. #define NODES_SHIFT     CONFIG_NODES_SHIFT 
  3. #else 
  4. #define NODES_SHIFT     0 
  5. #endif 
  6.  
  7. #define MAX_NUMNODES    (1 << NODES_SHIFT) 

因为CONFIG_NODES_SHIFT没有定义,所以NODES_SHIFT 为0

所以 MAX_NUMNODES 为1;

所以 for_each_node_state 定义如下:

  1. 470 #define for_each_node_state(node, __state) \ 
  2. 471  for ( (node) = 0; (node) == 0; (node) = 1) 

而此处的 node 对应 粉丝截图的nid, __state 对应 N_ONLINE

所以5765行代码,可以展开为

  1. for ( (nid) = 0; (nid) == 0; (nid) = 1) 

可见,nid被定义了。

三、宏定义的注意点

宏定义是一个给定名称的代码片段,当我们使用这个名称的时候,预处理器会自动将其替换为宏定义的内容。宏定义有两种,一种是object-like宏定义,在使用的时候相当于一个数据对象;另一种是function-like,在使用的时候就像调用函数那样。

1. 只占用编译时间

宏展开会使源程序变长,但是宏展开发生在编译过程中,不占运行时间,只占编译时间。

宏展开因为在预处理阶段发生,不会分配内存。

2. 宏替换发生时机

编译c源程序的过程:

宏替换发生在编译预处理阶段。

3. 预处理包括哪些工作

预处理产生编译器的输出,实现功能如下

1)文件包含

把#include中包含的内容拓展为文件的正文,即找到.h文件,同时展开到#include所在处

2)条件编译

根据#if和#ifdef等编译命令,将源程序文件中的部分包含进来,部分排除,排除在外的一般转换为空行

3)宏展开

将对宏的调用展开成相对应的宏定义

关于宏定义还有很多其他的知识点,本文暂不深入展开。

四、如何快速展开复杂的宏定义?

Linux内核中通常有很多宏定义,非常的复杂,对于初学者来说,经常会一头雾水,那如何快速理解宏定义呢?

一口君教你一个非常方便的方法,让你直接看透宏定义, 我们以上述代码为例:

第一步

  • 如该例所示,MAX_NUMNODES 就被嵌套了多级, 最终宏CONFIG_NODES_SHIFT在内核中没有检索到,所以该宏没有定义。

文件如下:123.c

  1. 1  
  2.  2  
  3.  3 #ifdef CONFIG_NODES_SHIFT 
  4.  4 #define NODES_SHIFT     CONFIG_NODES_SHIFT 
  5.  5 #else 
  6.  6 #define NODES_SHIFT     0 
  7.  7 #endif 
  8.  8  
  9.  9  
  10. 10                                                                                                                   
  11. 11 #define MAX_NUMNODES    (1 << NODES_SHIFT) 
  12. 12  
  13. 13  
  14. 14  
  15. 15  
  16. 16 #if MAX_NUMNODES > 1 
  17. 17 #define for_each_node_state(__node, __state) \ 
  18. 18         for_each_node_mask((__node), node_states[__state]) 
  19. 19 #else 
  20. 20 #define for_each_node_state(node, __state) \ 
  21. 21         for ( (node) = 0; (node) == 0; (node) = 1) 
  22. 22 #endif 
  23. 23  
  24. 24  
  25. 25  
  26. 26  
  27. 27 #define for_each_online_node(node) for_each_node_state(node, N_ONLINE) 
  28. 28  
  29. 29  
  30. 30 static int __build_all_zonelists(void *data) 
  31. 31 {    
  32. 32     int nid; 
  33. 33     int cpu; 
  34. 34     pg_data_t *self = data; 
  35. 35  
  36. 36      
  37. 37  
  38. 38     for_each_online_node(nid) { 
  39. 39         pg_data_t *pgdat = NODE_DATA(nid); 
  40. 40  
  41. 41         build_zonelists(pgdat); 
  42. 42         build_zonelist_cache(pgdat); 
  43. 43     } 
  44. 44 } 

第二步

使用以下命令,展开宏定义,

  1. gcc -E  

-E的含义是,编译预处理该文件,但是不去生成汇编代码,只把文件中的宏定义以及包含的头文件替代,并不会去检查语法正确与否。

结果如下:

  1. peng@ubuntu:~/test$ gcc 123.c -E 
  2. # 1 "123.c" 
  3. # 1 "<built-in>" 
  4. # 1 "<command-line>" 
  5. # 1 "/usr/include/stdc-predef.h" 1 3 4 
  6. # 1 "<command-line>" 2 
  7. # 1 "123.c" 
  8. # 28 "123.c" 
  9. static int __build_all_zonelists(void *data) 
  10.  int nid; 
  11.  int cpu; 
  12.  pg_data_t *self = data; 
  13.  
  14.  for ( (nid) = 0; (nid) == 0; (nid) = 1) { 
  15.   pg_data_t *pgdat = NODE_DATA(nid); 
  16.  
  17.   build_zonelists(pgdat); 
  18.   build_zonelist_cache(pgdat); 
  19.  } 

由结果可知, nid是被赋值为0的。

五、练习

我们来做一个练习,展开一下内核的waite_event()这个宏

拷贝用到所有宏定义到c文件中。

wait.c

  1. 1  
  2.  2 #define ___wait_event(wq, condition, state, exclusive, ret, cmd)    \ 
  3.  3     ({                                  \ 
  4.  4      __label__ __out;                       \ 
  5.  5      wait_queue_t __wait;                       \ 
  6.  6      long __ret = ret;                      \ 
  7.  7      \ 
  8.  8      INIT_LIST_HEAD(&__wait.task_list);             \ 
  9.  9      if (exclusive)                         \ 
  10. 10      __wait.flags = WQ_FLAG_EXCLUSIVE;          \ 
  11. 11      else\ 
  12. 12      {\ 
  13. 13      /* code */                         \ 
  14. 14      __wait.flags = 0;                  \ 
  15. 15      \ 
  16. 16      for (;;) {                         \ 
  17. 17      long __int = prepare_to_wait_event(&wq, &__wait, state);\ 
  18. 18      \ 
  19. 19      if (condition)                     \    
  20. 20      break;                     \ 
  21. 21      \ 
  22. 22      if (___wait_is_interruptible(state) && __int) {        \ 
  23. 23      __ret = __int;                 \ 
  24. 24          if (exclusive) {               \ 
  25. 25              abort_exclusive_wait(&wq, &__wait, \ 
  26. 26                      state, NULL);  \ 
  27. 27                  goto __out;                \ 
  28. 28          }                      \ 
  29. 29      break;                     \ 
  30. 30      }                          \ 
  31. 31      \ 
  32. 32          cmd;                           \ 
  33. 33      }                              \ 
  34. 34      finish_wait(&wq, &__wait);                 \ 
  35. 35          __out: __ret;                              \ 
  36. 36      })\ 
  37. 37     }\ 
  38. 38  
  39. 39  
  40. 40  
  41. 41  
  42. 42 #define TASK_UNINTERRUPTIBLE    2 
  43. 43  
  44. 44  
  45. 45 #define __wait_event(wq, condition)                 \ 
  46. 46     (void)___wait_event(wq, condition, TASK_UNINTERRUPTIBLE, 0, 0,  \ 
  47. 47             schedule())\ 
  48. 48 \ 
  49. 49 \ 
  50. 50 wait_event(wq, condition)                   \ 
  51. 51         do {                                    \ 
  52. 52             if (condition)                          \ 
  53. 53                 break;                          \ 
  54. 54                     __wait_event(wq, condition);                    \ 
  55. 55         } while (0)\ 
  56. 56  
  57. 57  
  58. 58  
  59. 59 test() 
  60. 60 { 
  61. 62     wait_event(wq,flag == 0); 
  62. 64 } 

编译与处理结果如下:

  1.  root@ubuntu:/home/peng/test# gcc wait.c -E 
  2. # 1 "wait.c" 
  3. # 1 "<built-in>" 
  4. # 1 "<command-line>" 
  5. # 1 "/usr/include/stdc-predef.h" 1 3 4 
  6. # 1 "<command-line>" 2 
  7. # 1 "wait.c" 
  8. # 71 "wait.c" 
  9. test() 
  10.  do { if (flag == 0) break; (void)({ __label__ __out; wait_queue_t __wait; long __ret = 0; INIT_LIST_HEAD(&__wait.task_list); if (0) __wait.flags = WQ_FLAG_EXCLUSIVE; else { __wait.flags = 0; for (;;) { long __int = prepare_to_wait_event(&wq, &__wait, 2); if (flag == 0) break; if (___wait_is_interruptible(2) && __int) { __ret = __int; if (0) { abort_exclusive_wait(&wq, &__wait, 2, NULL); goto __out; } break; } schedule(); } finish_wait(&wq, &__wait); __out: __ret; }) }; } while (0); 

函数test()整理如下:

  1. test(){ 
  2.  do {  
  3.   if (flag == 0)  
  4.   break;  
  5.   (void)( 
  6.   { 
  7.    __label__ __out;  
  8.    wait_queue_t __wait;  
  9.    long __ret = 0;  
  10.    INIT_LIST_HEAD(&__wait.task_list);  
  11.    if (0) __wait.flags = WQ_FLAG_EXCLUSIVE;  
  12.    else { 
  13.     __wait.flags = 0;  
  14.  
  15.    for (;;)  
  16.    {  
  17.     long __int = prepare_to_wait_event(&wq, &__wait, 2);  
  18.     if (flag == 0)  
  19.      break;  
  20.     if (___wait_is_interruptible(2) && __int)  
  21.     {  
  22.      __ret = __int; 
  23.      if (0)  
  24.      {  
  25.       abort_exclusive_wait(&wq, &__wait, 2, NULL);  
  26.       goto __out;  
  27.      }  
  28.      break;  
  29.     }  
  30.     schedule();  
  31.    }  
  32.    finish_wait(&wq, &__wait); 
  33. __out:  
  34.  __ret;  
  35.    })  
  36.   };  
  37.  }while (0); 

这就是wait_event()最终被替换后的代码,你学会了吗?

六、16个经典宏定义小例子

数值相关的宏定义

1 闰年的判断 ,年份可以整除4并且不能整除100,或者可以整除400,则为闰年;

  1. #define IS_LEAP_YEAR(y) (((((y) % 4) == 0) && (((y) % 100) != 0))  \ 
  2.          || (((y) % 400) == 0))/*判断是否是闰年*/ 

2 **MAX 与 MIN ** ;

  1. #define MAX(x, y)   (((x) < (y)) ? (y) : (x)) /*两数取最大数*/ 
  2. #define MIN(x, y)   (((x) < (y)) ? (x) : (y)) /*两数取最小数*/ 

3 BCD码;

  1. #define BCD2HEX(x) (((x) >> 4) * 10 + ((x) & 0x0F))       /*BCD码转数值, 20H -> 20*/ 
  2. #define HEX2BCD(x) (((x) % 10) + ((((x) / 10) % 10) << 4))  /*数值转BCD码, 20 -> 20H*/ 

4 字符相关的宏定义

字符范围判断

  1. /*字符是否在某个区间范围内*/ 
  2. #define in_range(c, lo, up)  ((uint8)c >= lo && (uint8)c <= up)   
  3.  
  4.  
  5. #define isprint(c)           in_range(c, 0x20, 0x7f) 
  6.    /*十进制内字符*/ 
  7. #define isdigit(c)           in_range(c, '0', '9') 
  8. /*十六进制内字符*/ 
  9. #define isxdigit(c)          (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F')) 
  10. /*是否是小写*/ 
  11. #define islower(c)           in_range(c, 'a', 'z')  
  12. /*是否是空格*/ 
  13. #define isspace(c)           (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v') 
  14. /*是否为ASCII码*/ 
  15. #define isascii(c)          ((unsigned) (c) <= 0177)  

5 byte相关的宏定义

  1. #define MSB(x) (((x) >> 8) & 0xff) /* x占2byte(如short)2byte的高地址的1byte */ 
  2. #define LSB(x) ((x) & 0xff) /* x占2byte(如short)2byte的低地址的1byte*/ 
  3.  
  4. #define MSW(x) (((x) >> 16) & 0xffff) /* x占4byte(如int)  4byte的高地址的2byte */ 
  5. #define LSW(x) ((x) & 0xffff)         
  6. #define WORDSWAP(x) (MSW(x) | (LSW(x) << 16)) /* x占4byte(如int) 低2字节与高2字节内容交换 */  
  7.  
  8. #define LLSB(x) ((x) & 0xff) /*x占4byte(如int) 取低地址1byte*/      
  9. #define LNLSB(x) (((x) >> 8) & 0xff) 
  10. #define LNMSB(x) (((x) >> 16) & 0xff) 
  11. #define LMSB(x)  (((x) >> 24) & 0xff) 
  12. /*x占4byte(如int) 4字节逆序*/ 
  13. #define LONGSWAP(x) ((LLSB(x) << 24) \     
  14.      |(LNLSB(x) << 16) \ 
  15.      |(LNMSB(x) << 8) \ 
  16.      |(LMSB(x))) 

6 bit相关的宏定义

  1. /* 判断某位是否为1 */ 
  2. #define BIT_IS_1(x,y) (((x)>>(y))&0x01u)    
  3.  
  4. #define SETBITS(x,y,n) (x) = (n) ? ((x)|(1 << (y))) : ((x) &(~(1 << (y)))); 
  5. /* 给某位置反 */ 
  6. #define BIT_INVERSE(x,y)    ((x)=(x)^(1<<(y)))         
  7. /* 字节串中某BIT值*/ 
  8. #define BIT_OF_BYTES(x, y) (BITS(x[(y)/8], (y)%8)) 
  9. /* 字节串中设置某BIT为0 */       
  10. #define SETBITSTO0_OF_BYTES(x, y) (x[(y)/8]) &= (~(1 << ((y)%8))) 
  11. /* 字节串中设置某BIT为1 */   
  12. #define SETBITSTO1_OF_BYTES(x, y) (x[(y)/8]) |= (1 << ((y)%8))  

7 数组与结构体相关的宏定义

  1. /* number of elements in an array */ 
  2. #define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0]))         
  3. /* byte offset of member in structure*/ 
  4. #define MOFFSET(structure, member) ((int) &(((structure *) 0) -> member))    
  5. /* size of a member of a structure */ 
  6. #define MEMBER_SIZE(structure, member) (sizeof (((structure *) 0) -> member))  

8 对齐的宏定义

  1. /*向上对齐,~(align - 1)为对齐掩码,例如align=8,~(align - 1) = ~7, 
  2. (~7)二进制后三位为000,&(~(align - 1)) = &(~7),就是去掉余数,使其能被8整除*/ 
  3. #define ALIGN_UP(x, align)  (((int) (x) + (align - 1)) & ~(align - 1))  
  4. /*向下对齐*/ 
  5. #define ALIGN_DOWN(x, align)    ((int)(x) & ~(align - 1)) 
  6. /*是否对齐*/ 
  7. #define ALIGNED(x, align)   (((int)(x) & (align - 1)) == 0) 
  8.  
  9. /*页面对齐相关的宏,一页为4096字节*/ 
  10. #define PAGE_SIZE         4096 
  11. #define PAGE_MASK         (~(PAGE_SIZE-1)) 
  12. #define PAGE_ALIGN(addr) -(((addr)+PAGE_SIZE-1) & PAGE_MASK) 

9 防止头文件被重复包含

  1. #ifndef BODY_H   //保证只有未包含该头文件才会将其内容展开 
  2.  
  3. #define BODY_H 
  4.  
  5. //头文件内容 
  6.  
  7. #endif 

10 得到指定地址上的一个字节或者一个字

  1. #define MEM_B(x) (*(byte*)(x))    //得到x表示的地址上的一个字节 
  2. #define MEM_W(x) (*(word*)(x))    //得到x表示的地址上的一个字 

11 得到一个field在结构体中的偏移量

  1. #define OFFSET(type,field) (size_t)&((type*)0->field) 

12 得到一个结构体中field所占用的字节数

  1. #define FSIZ(type,field) sizeof(((type*)0)->field) 

13 得到一个变量的地址

  1. #defien B_PTR(var) ((byte*)(void*)&(var))   //得到字节宽度的地址 
  2. #define W_PTR(var) ((word*)(void*)&(var))   //得到字宽度的地址 

14 将一个字母转换成大写

  1. #define UPCASE(c) (((c) >= "a" && (c) <= "z") ? ((c) - 0x20) : (c) ) 

15 防止溢出

  1. #define INC_SAT(val) (val = ((val) +1 > (val)) ? (val) + 1 : (val)) 

16 返回数组元素的个数

  1. #define ARR_SIZE(a) (sizeof( (a) ) / sizeof(a[0]) ) ) 

相关内容