函数的声明和定义的区别(一)

函数的声明和编译的区别:

  1. 声明是给出函数返回类型,传入参数类型,不必进行具体的固定流程
void funcA(int);
  1. 定义则是具体的
#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
  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

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值