关于c语言不同文件之间直接函数接口引用的简介

来源:互联网 发布:mac os 卸载软件 编辑:程序博客网 时间:2024/06/14 21:20
在工作中,很多情况下是当前正编辑的A程序的函数接口中需要调用到B文件内部定义的函数接口,
通常情况下我们有如下两种处理方式:
1. 将B文件中A用到的B文件的函数接口放置在B.h文件中,A函数所在文件引用到B.h文件即可;
2. 就是直接在A所在的文件中用:extern func();声明引用。
一般情况下,为了程序的刻度性选用第一种处理方式,但是也不是所有的情况第一种都适用,
比如:在A函数接口中引用到的B文件的函数接口用到了非B或者B.h文件定义的结构体等情况,
这时,若在B.h中声明引用到的函数接口,就会提示你用到了未定义或未知类型的数据结构,
然而当你将包含这个数据类型的结构时,又可能会出现其他的一些错误,比如未知的类型声明或使用,
具体的例子讲解如下


方案 1:
curr.c
struct student{
int id;
int num;
int score;
char name[20];
}STU;
func A()
{
STU stu;
int m, n;
struct 
b(m,n);
c(stu);

return 0;
}


B.c 


b(int m, int n)
{
...
}


c(STU stu)
{
...
}


B.h


extern b(int m, int n);
extern c(STU stu);


方案2:
curr.c
struct student{
int id;
int num;
int score;
char name[20];
}STU;


extern b(int m, int n);
extern c(STU stu);


func A()
{
STU stu;
int m, n;
struct 
b(m,n);
c(stu);

return 0;
}


B.c 


b(int m, int n)
{
...
}


c(STU stu)
{
...

}

像上面的这种情况,就是和方案2,因为STU类型是在A.c文件中定义,而B文件中又无法引用到这个结构,多以最好的方法就是按照方案2操作比较节省精力。

1 0
原创粉丝点击