c语言多个子函数声明,C函数在多个源文件中的声明和定义
這是src1.c的內(nèi)容:
#include
extern int w;
//int go(char); // no need to declare here. WHY????
main(){
char a='f';
go(a);
printf("%d\n", w);
}
這是src2.c的內(nèi)容:
#include
int w = 99;
int go(char t){
printf("%c\n%d\n",t,sizeof(t));
}
為什么在Linux中編譯后,在src1.c文件中聲明go函數(shù)是不是必須?
cc src1.c src2.c;
編譯器是否將src2.c文件中的go函數(shù)定義放在main函數(shù)的代碼上面,這樣就不需要聲明了?
我這樣做:
#include
int go(char); // need to declare here, because if not, arguments of go will be promoted to intS and they would conflict with char parameters defined in go. Error is droped!
main(){
char a='f';
go(a);
}
int go(char t){
printf("%c\n%d\n",t,sizeof(t));
}
所以每個人都說,在沒有原型的情況下傳遞任何數(shù)量和類型的參數(shù)是錯誤的.在這種情況下,它們被提升為整數(shù),但必須同意定義中指定的那些.
我做了一些測試,發(fā)現(xiàn)即使它編譯沒有錯誤它也無法正常工作.
SRC1:
#include
int go(int t){
printf("%d\n%d\n",t,sizeof(t));
}
sr2.c:
#include
int go(int); //if I omit this prototype, program outputs 1 which is far from correct answer :)
main(){
double b=33453.834;
go(b);
}
所以最后答案只能是未定義的行為.
謝謝Maxim Skurydin
總結
以上是生活随笔為你收集整理的c语言多个子函数声明,C函数在多个源文件中的声明和定义的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 思科nat配置实例_Cisco ASA
- 下一篇: java如何对list进行排序_java