一、函数的由来
二、模块化程序设计
三、c 语言中的模块化
四、面向过程的程序设计
- 面向过程是一种以过程为中心的编程思想
- 首先将复杂的问题分解为一个个容易解决的问题
- 分解过后的问题可以按照步骤一步步完成
- 函数是面向过程在 c 语言中的体现
- 解决问题的每个步骤可以用函数来实现
五、声名和定义
- 声明的意义在于告诉编译器程序单元的存在
- 定义则明确指示程序单元的意义
- c 语言中通过 extern 进行程序单元的声明
- 一些程序单元在声明时可以省略 extern
严格意义上的声明和定义并不相同!
下面看一个例子:
test.c:
#include <stdio.h> #include <malloc.h> extern int g_var; //声明 extern struct test; //声明 int main() { extern void f(int i, int j); //声明 extern int g(int x); //声明 struct test* p = null; // (struct test*)malloc(sizeof(struct test)); printf("p = %p\n", p); //g_var = 10; printf("g_var = %d\n", g_var); f(1, 2); printf("g(3) = %d\n", g(3)); free(p); return 0; }
global.c:
#include <stdio.h> /*下面都是定义*/ int g_var = 10; struct test { int x; int y; }; void f(int i, int j) { printf("i + j = %d\n", i + j); } int g(int x) { return (int)(2 * x + g_var); }
输出结果如下:
怎么证明声明和定义不同呢?我们对 test.c 修改成这样,将 struct test* p = null; 改成 struct test* p = (struct test*)malloc(sizeof(struct test));
#include <stdio.h> #include <malloc.h> extern int g_var; extern struct test; int main() { extern void f(int i, int j); extern int g(int x); struct test* p = (struct test*)malloc(sizeof(struct test)); printf("p = %p\n", p); //g_var = 10; printf("g_var = %d\n", g_var); f(1, 2); printf("g(3) = %d\n", g(3)); free(p); return 0; }
可以看到,直接报错:
delphi@delphi-vm:~$ gcc test.c global.c
test.c:6: warning: useless storage class specifier in empty declaration
test.c: in function ‘main’:
test.c:13: error: invalid application of ‘sizeof’ to incomplete type ‘struct test’
这是因为编译器在 test.c 是找不到 struct test 的定义的,只有 struct test 的声明,因此无法知道 struct test 结构体的信息。(c 语言编译器编译 c 文件的时候不会依赖于文件之间的编译顺序)。
六、小结
- 函数是面向过程思想在 c 语言中的体现
- 面向过程是由上至下分解问题的设计方法
- 程序中的定义和声明完全不同
- c 语言中通过 extern 对程序单元进行声明
到此这篇关于c语言深入探究函数的溯源的文章就介绍到这了,更多相关c语言 函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!