第一時間看干貨文章 ?【干貨】嵌入式驅動工程師學習路線 ?【干貨】Linux嵌入式知識點-思維導圖-免費獲取 ?【就業】一個可以寫到簡歷的基于Linux物聯網綜合項目 ?【就業】簡歷模版
某個函數fun_1()是在lib內,沒法修改的,在程序中大量的使用了該函數,現在想把原本fun_1失效(現在失效的方法是#define fun_1(..)),用另外一個函數fun_2(),可是fun_2最后也需要調用fun_1,上面的失效方法感覺就不行了,請問怎么做才對?

粉絲提問,必須安排!一口君實力寵粉!
想學習C語言、Linux、驅動、ARM的同學可以加一口君微信,拉你進群。
我把問題簡單整理下:

如果我們要使用一個和庫函數相同名字的函數,就要借助static關鍵字。
在函數的返回類型前加上static,就是靜態函數。其特性如下:
系統調用函數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 fail\n");
16 return;
17 }
18 read(fd,buf,16);
19 printf("enter test():%s\n",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().
函數調用順序如下:

問題解決了,你學到了嗎?
end
一口Linux
關注,回復【1024】海量Linux資料贈送
精彩文章合集
文章推薦