关于多个.c和.h文件时的相互调用

来源:互联网 发布:云科数据云一体机 编辑:程序博客网 时间:2024/06/06 00:01

假如  有一个头文件 1.h 和源文件1.c

      还有一个头文件 2.h和源文件2.c

 

函数的调用

假如 有一个函数 在1.h 中声明 void xuexi(void)

                在1.c中实现:先包含 #include "1.h"

                              void xuexi(void)

                               {

                                 函数的实现;

                                }

           

     还有一个函数 在2.h中声明 void xuexi2(void)

                  在2.c中实现先包含 #include "2.h"

                                 void xuexi2(void)

                                {

                                   函数的实现;

                                 }

      如果我们要在1.c中调用2.c中的函数  void xuexi2(void),我们只需要#include "2.h",就可以了。                     例如: 在1.c中

                               #include "1.h"

                               #include "2.h"

                               xuexi();

                               xuexi2();  //2中的函数  

   

变量的调用

比如在2.c中定义一个变量int a(注意:在.h中不能定义变量,只能在.c中定义变量),比如:

                              #include "2.h"

                              在2.c中定义

                               int a;

 

如果我们想在1.c中调用这个变量

          那么   在1.c中需要extern int a;(如果不用2.c中的函数,可以不加#include"2.h")

                 在1.h中extern int a也可以,因为1.c中#include "1.h"了

最好的方法:我们可以在2.h中 extern int a;如果我们想在1.c中使用这个变量 int a,那么我们只需要include"2.h"就可以了。

 

 

 

宏定义的调用

假如在2.h中定义了几个宏定义:#define   1

                             #define    2

(注意:尽量在.h中定义宏定义)

           

如果我们想在1.c中使用这几个宏,只需要在1.c中#include "2.h",就可以了。


转自:http://blog.sina.com.cn/s/blog_af08990101019pog.html

原创粉丝点击