一杯清酒邀明月
天下本无事,庸人扰之而烦耳。
posts - 3121,comments - 209,views - 578万

  假设A模块是需要调用B模块,而B模块又需要调用A模块,我们知道,模块之间的调用需要包含头文件,那模块的相互调用就存在头文件的相互包含,结果,你自己试试就知道了。不相互包含又不行,下面我们给出行不通的方式(我用main.c来模拟A模块,用test.c来模拟B模块):

main.c内容如下:

复制代码
 1 #include <stdio.h>
 2 #include "test.h"
 3  
 4 void print();
 5  
 6 int main()
 7 {
 8     fun();
 9     return 0;
10 }
11  
12 void print()
13 {
14     printf("hello world\n");
15 }
复制代码

test.c内容如下:

复制代码
1 #include <stdio.h>
2 #include "test.h"
3  
4 void fun()
5 {
6     printf("test\n");
7     print();
8 }
复制代码

test.h内容如下:

1 void fun();

      编译不过,因为在test.c中,print函数式不可见的。下面,我们来采用回调函数实现吧(本质是主动把函数地址传过去):

main.c的内容如

复制代码
 1 #include <stdio.h>
 2 #include "test.h"
 3  
 4 void callBackPrint();
 5  
 6 int main()
 7 {
 8     fun(callBackPrint);
 9     return 0;
10 }
11  
12 void callBackPrint()
13 {
14     printf("hello world\n");
15 }
复制代码

test.c的内容如下:

复制代码
1 #include <stdio.h>
2 #include "test.h"
3  
4 void fun(void (*p)())
5 {
6     printf("test\n");
7     (*p)();
8 }
复制代码

test.h的内容如下:

1 void fun(void (*p)());

  可以正确编译运行,现在,懂了回调函数的作用了吧?如此美妙,妙哉妙哉。如果你开发经验非常丰富,你会发现,回调机制无处不在。

  总结一下: 先注册(把函数地址传过去), 后回调(根据传过来的函数地址, 调用函数)。

posted on   一杯清酒邀明月  阅读(157)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示