当前位置:网站首页>C编译器 - 隐式函数声明
C编译器 - 隐式函数声明
2022-06-29 06:41:00 【qazw9600】
引子
- 初学者使用C语言编程,有时会出现异常崩溃,如下:
* test.c
#include <stdio.h>
int main(){
printf("%s\n", test());
return 0;
}
* xxx.c
char *test(){
return "hello world";
}
* 编译
gcc test.c xxx.c -o test
* 执行
xxx:~/demo$ ./test
段错误 (核心已转储)
问题原因
- 在C语言中,如果函数在调用前未声明,编译器不会报错,只是提示警告,如果函数未定义,在链接时会报错提示函数undefined。
- 如果没有函数声明,编译器如何得知参数个数以及返回类型?编译器编译时是以单个代码文件为编译单元,函数未声明,编译器是无法得知函数的参数个数等信息,链接时才会找到函数定义,编译器会按照默认规则,为调用函数的C代码产生汇编代码。
隐式函数声明
- 编译器的默认规则即为隐式函数声明,如果函数未声明,编译器默认按照如下声明进行函数调用。
int function();
可能导致的问题
- 如果隐式函数声明可能与真实定义不同,可能导致异常,并且有些异常不容易被发现。
- 函数定义中返回类型非int
- 如引子中的例子,真实返回的是char *类型,按照隐式函数声明转换成int后,最后调用printf将该值当做字符串的内存地址去访问,访问的是一个错误地址,所以导致程序崩溃。
- 如果真实返回的是long类型,转换成int后可能导致数据被截断。
- 函数定义中参数类型和调用不匹配
- 例如:
* test.c
#include <stdio.h>
int main(){
test(1)
return 0;
}
* xxx.c
int test(char *a){
printf("%s\n", a);
return 0;
}
- 以上程序编译后运行会崩溃。
问题避免
- 为了避免该问题,程序员需要重视编译器给出的关于隐式声明的警告,及时通过包含必要的头文件来消除这种警告。
- 有些情况下,gcc编译器甚至不会提示警告信息,使用C语言的C99版本中,无论如何都会给出警告,而C++编译器则更严格,不再支持隐式函数声明,如果函数未声明,将直接报错。
边栏推荐
- 道闸控制器通讯协议
- 软件测试鸾音鹤信
- Select distinct on statement in kingbasees
- 关于KingbaseES临时文件过大问题
- Listen to textarea input through Keyup to change button style
- 【深度之眼吴恩达机器学习作业班第四期】Logistic Regression 逻辑回归总结
- Common MySQL errors and solutions summarized painstakingly (I)
- pycharm的虚拟环境如何共享到jupyter-lab
- Little white battle pointer (Part 1)
- 查看tensorflow是否支持GPU,以及测试程序
猜你喜欢
随机推荐
SQL 注入绕过(六)
Some examples.
Electric check code configuration
matlab simulink 电网扫频仿真和分析
Markdown skill tree (7): separator and reference
Schnuka: visual positioning system manufacturer what is a visual positioning system
Detailed explanation of route (Jiuyang Scripture)
101. 对称二叉树(递归与迭代方法)
Compiling principle: the king's way
tf. compat. v1.global_ variables
ES中配置ext.dic文件不生效的原因
Mmclassification installation and debugging
Schnuka: 3D visual inspection scheme 3D visual inspection application industry
pycharm的虚拟环境如何共享到jupyter-lab
蓝桥杯——13届第二批试题解析
Listen to textarea input through Keyup to change button style
【工控老马】单片机与西门子S7-200通信原理详解
KingbaseES 中select distinct on 语句
【量化投资系统】因子处理安装talib
Select distinct on statement in kingbasees









