变量定义

给你下面三个示例文件:kbi.h, kbi.c, other.c

kbi.h

  1. #ifndef __KBI_H_
  2. #define __KBI_H_
  3. #ifdef  __KBI_C_
  4. #define KBI_EXT
  5. #else
  6. #define KBI_EXT extern
  7. #endif
  8. KBI_EXT int a;
  9. KBI_EXT int b;
  10. KBI_EXT int c;
  11. #endif /* __KBI_H_ */
复制代码


kbi.c

  1. #define __KBI_C_
  2. #include "kbi.h"
  3. int get_a(void){
  4.   return a;
  5. }
复制代码




other.c

  1. #include "kbi.h"
  2. int use_c(void){
  3.   return c;
  4. }
复制代码



解释:
由于kbi.h是公共头文件,可以在多个C文件中用include包含。有了KBI_EXT这样的定义,就可以保证只在一个C文件(这里举例的是kbi.c)定义变量,而在其它C文件中只是引用。这样即方便变量的管理又可以避免重定义错误。

原文:http://www.amobbs.com/thread-5631875-1-1.html

原文地址:https://www.cnblogs.com/hwl1023/p/4789596.html