问题描述:
某个函数fun_1()是在lib内,没法修改的,在程序中大量的使用了该函数,现在想把原本fun_1失效(现在失效的方法是#define?fun_1(..)),用另外一个函数fun_2(),可是fun_2最后也需要调用fun_1,上面的失效方法感觉就不行了,请问怎么做才对?
粉丝提问
粉丝提问,必须安排!一口君实力宠粉!
想学习C语言、Linux、驱动、ARM的同学可以加一口君微信,拉你进群。
我把问题简单整理下:
问题
- 我们库文件里有个函数是read()我们现在要自己定义一个名字一样的函数read(),main()函数首先调用我们自己定义的函数read()自己定义的函数,要再定义库文件中的read()函数。
问题就出在如何让我们自己定义的read()函数只调用lib库中的read函数,而不会调用自己。
解决思路-static
如果我们要使用一个和库函数相同名字的函数,就要借助static关键字。
在函数的返回类型前加上static,就是静态函数。其特性如下:
- 静态函数只能在声明它的文件中可见,其他文件不能引用该函数不同的文件可以使用相同名字的静态函数,互不影响其他库如果有相同的函数名,优先使用本文件的静态函数
举例
系统调用函数read(),定义如下:
read
现在我们想定义一个自己的函数,名字也是read,要如何操作呢?
#include?<stdio.h>
#include?<sys/types.h>
#include?<sys/stat.h>
#include?<fcntl.h>
static?void?read()
{
?printf("my read func()n");
}?
int?main()
{
?read();
}
执行结果
我们可以看到,虽然我们添加了系统调用read()的头文件,但是调用的是我们自己定义的read()函数。
下面我们来看下,如果我们定义的read函数又想调用系统调用read()函数应该怎么办呢?那就必须再增加一个文件,把相关功能放到另外一个文件中,在同一个文件中是没有办法实现的。
上代码,没有论据的知识点都是耍流氓。【一口君绝大部分文章都是有实例代码支撑】
//test.c
??1#include?<stdio.h> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
2#include?<sys/types.h>
3#include?<sys/stat.h>
4#include?<fcntl.h>
5
6
7void?test()
? 8?{
9? ? ?int?fd;
10? ? ?char?buf[128]={0};
11
12? ? ?fd = open("123.c",O_RDWR);
13? ? ?if(fd<0)
14? ? ?{
15? ? ? ? ?perror("open failn");
16? ? ? ? ?return;
17? ? ?}
18? ? ?read(fd,buf,16);
19? ? ?printf("enter test():%sn",buf);
20?}
//123.c
??1#include?<stdio.h> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
2#include?<sys/types.h>
3#include?<sys/stat.h>
4#include?<fcntl.h>
5
6extern?void?test();
7static?void?read()
8?{
9? ? ?printf("my read func()n");
10? ? ?test();
11?}
12?int?main()
13?{
14? ? ?read();
15?}
执行结果
执行结果
由执行结果可知,程序既调用到了我们自己调用的read()函数,也调用到了系统调用函数read().
函数调用顺序如下:
调用顺序
问题解决了,你学到了吗?
275