当前位置:网站首页>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++编译器则更严格,不再支持隐式函数声明,如果函数未声明,将直接报错。
边栏推荐
- Kyushu cloud helps Inner Mongolia's "counting from the east to the west" project to drive the smart new ecology of the surveying and mapping industry
- 【工控老马】基于PLC的花样喷泉设计原理详解
- Reflection modification final
- matlab 多普勒效应产生振动信号和处理
- 数组知识点小结
- 【工控老马】PLC六路抢答器系统设计详解
- 施努卡:轮胎自动抓取安装,3D视觉定位,机器人自动抓取
- Schnuka: automatic tire grabbing installation, 3D visual positioning, automatic robot grabbing
- Software testing
- VMware vcenter/ESXI系列漏洞总结
猜你喜欢

软件测试鸾音鹤信

Roblox剑九之剑二

tf. count_ nonzero

Appium 环境搭建

Handle series - install spotbugs and use them quickly

施努卡:3d机器视觉检测系统 3d视觉检测应用行业
![[industrial control old horse] detailed design of PLC six way responder system](/img/9c/8bfe336bb95a028a4fb8130941ff81.png)
[industrial control old horse] detailed design of PLC six way responder system

Software testing

感知健康生活 赋能无界连接 ——为OpenHarmony 3.1生态构建贡献芯海力量

Schnuka: 3D machine vision inspection system 3D vision inspection application industry
随机推荐
施努卡:视觉定位系统厂家 什么是视觉定位系统
[translation] E-Cloud. Large scale CDN using kubeedge
Problem solving -- > online OJ (13)
[old horse of industrial control] detailed explanation of Siemens PLC s7-300scl programming
Using cdockablepane to realize floating window in MFC
【量化投资系统】问题记录及解决方法
Markdown skill tree (8): code blocks
Check whether tensorflow supports GPU and test program
Blue Bridge Cup - minimum frame
Gateway controller communication protocol
1032 Sharing
tf. to_ int64
Schnuka: 3D machine vision inspection system 3D vision inspection application industry
postman预处理/前置条件Pre-request
100 lectures on Excel advanced drawing skills (VI) - practical application cases of Gantt chart in project progress
tf.to_int64
tf.compat.v1.global_variables
【工控老马】PLC六路抢答器系统设计详解
Postman pre request
Common MySQL errors and solutions summarized painstakingly (I)