目录一、函数的由来二、模块化程序设计三、C 语言中的模块化四、面向过程的程序设计五、声名和定义六、小结一、函数的由来 二、模块化程序设计 三、C 语言中的模块化 四、面向过程的
严格意义上的声明和定义并不相同!
下面看一个例子:
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语言 函数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: C语言深入探究函数的溯源
本文链接: https://www.lsjlt.com/news/146285.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0