gpt4 book ai didi

c - 具有没有原型(prototype)的旧式函数的 C 编译器的行为

转载 作者:太空狗 更新时间:2023-10-29 14:54:32 25 4
gpt4 key购买 nike

当我的程序包含两个文件时:

主.c

#include <stdio.h>

int main(void) {
printf("%lf\n",f());
return 0;
}

函数.c

double f(int a) {
return 1;
}

编译器没有显示任何错误。

当我的程序只包含一个文件时:

主.c

#include <stdio.h>

int main(void) {
printf("%lf\n",f());
return 0;
}

double f(int a) {
return 1;
}

Visual C++ 2008 编译器显示以下错误:

Error 2 error C2371: 'f' : redefinition; different basic types d:\temp\projects\function1\function1\1.c 8 function1

谁能解释这种奇怪的行为?

最佳答案

C 将假定函数具有原型(prototype) int func();除非你另有说明。(注意在 C 中 int func(); 和 int func(void); 是不同的东西)

在第二种情况下,您调用了 f(),编译器没有看到任何原型(prototype),因此它假设它是 int f(); 。稍后它会看到您对具有不同原型(prototype)的 f() 的定义 - 并发出错误。

这不会发生在 1. 的情况下,因为它们在不同的编译单元中。

关于c - 具有没有原型(prototype)的旧式函数的 C 编译器的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2287164/

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