gpt4 book ai didi

c - 将参数传递给不同文件中的函数(gcc)

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:58 30 4
gpt4 key购买 nike

我在 Add.c 中为 int 写了一个 add 函数。然后,我将实数传递给 Main.c 中的这个 add 函数。代码如下所示。

如果我在调用之前有 add 函数的声明,则答案正确为 30。但是,如果声明不存在,则答案不正确。为什么?

添加.c

int add(int x, int y) { return x + y;}

主要.c

#include<stdio.h>
int add(int, int); // If this does not exist, the answer is not 30.
int main(void) {
printf("%d\n", add(10.5, 20.5));
}

最佳答案

如果没有声明,更具体地说是原型(prototype)(具有指定参数类型的声明),您将依赖函数的隐式无原型(prototype)声明(现在是 C 的过时功能)。

函数 f 的隐式原型(prototype)是 int f()——一个返回 int 并采用未指定数量参数的函数。

调用没有原型(prototype)的函数的方式是参数被提升(小于int 整数类型到intfloats 到 doubles) 并以实现定义的方式传递给函数。如果参数与定义不匹配,则行为未定义(您的情况)。

您可以通过提供显式强制转换来解决此问题(同时仍然依赖隐式声明):

#include<stdio.h>
//nothing (probably will get a compiler warning) or
int add(); /*=params unspecified*/
int main(void) {
printf("%d\n", add((int)10.5, (int)20.5));
}

从而移除 UB(未定义的行为),或者您可以包含原型(prototype),这将使​​编译器转换传入的 float 以匹配预期的类型(int )。换句话说,对于原型(prototype),编译器会为您插入这些强制转换,在(参数)赋值中看到从 floatint 的转换。

解决此问题的首选方法是通过 header 包含原型(prototype),该 header 也包含在实现文件 (Add.c) 中,以便允许编译器验证调用是否与定义一致。

关于c - 将参数传递给不同文件中的函数(gcc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50599369/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com