函数的声明和编译的区别:
- 声明是给出函数返回类型,传入参数类型,不必进行具体的固定流程
void funcA(int);
- 定义则是具体的
#include<stdio.h>
void funcA(int n) {
if(n == 0) return ;
printf("funcA = %d\n", n );
funcA(n - 1);
}
int main() {
funcA(5);
return 0;
}
像这样写,函数的定义过程就完成了
没有什么问题,编译后输出如下
funcA = 5
funcA = 4
funcA = 3
funcA = 2
funcA = 1
- 函数声明一般放在函数声明之前,可以直接调用;
那么当我们将funcA中调用的函数修改为没有声明、定义的函数funcB会发生什么呢?
#include<stdio.h>
void funcA(int n){
if(n == 0) return ;
printf("funcA = %d\n", n );
funcB(n - 1);
}
int main() {
funcA(5);
return 0;
}
编译报错如下:
test2.cpp:14:2: error: use of undeclared identifier 'funcB'; did you mean
'funcA'?
test2.cpp:11:6: note: 'funcA' declared here
void funcA(int n) {
^
1 error generated.
这个错误显示我的funcB函数没有得到声明,那么我进行简单的声明。
由于函数编译时从前向后的,那么我们把声明语句放到前面,不进行具体的定义。
#include<stdio.h>
void funcB(int);
void funcA(int n){
if(n == 0) return ;
printf("funcA = %d\n", n );
funcB(n - 1);
}
int main() {
funcA(5);
return 0;
}
这次直接进行编译的错误是什么呢?
error: linker command failed with exit code 1 (use -v to see invocation)
这个错误表明文件在链接阶段出现了错误。
总结一下:
1. 函数没有声明,报错undeclared
2. 函数声明而未定义,报错linker command failed