为了便于理解,写一个简单点的demo
#include <stdio.h>
int Add(int a,int b){
return a+b;
}
int Mul(int a,int b){
return a*b;
}
int main(){
int first,second,result;
printf("请输入第一个数:\n");
scanf("%d",&first);
printf("请输入第二个数:\n");
scanf("%d",&second);
printf("加法结果:%d\n",Add(first,second));
printf("乘法结果:%d\n",Mul(first,second));
return 0;
}
运行结果:
作为以后工程项目中常用的分文件编程思想,就需要对其进行加工一下,将主函数和功能函数分开到两个文件中,如果只是单纯的分开像这样:
int Add(int a,int b){
return a+b;
}
int Mul(int a,int b){
return a*b;
}
#include <stdio.h>
int main(){
int first,second,result;
printf("请输入第一个数:\n");
scanf("%d",&first);
printf("请输入第二个数:\n");
scanf("%d",&second);
printf("加法结果:%d\n",Add(first,second));
printf("乘法结果:%d\n",Mul(first,second));
return 0;
}
在树莓派中运行时就会出现这种情况:
报warning!可以正常运行文件!
但实际情况下,其实应该会报错,因为树莓派下的gcc比较智能,自动将两个文件进行了整合,编译出一个.out文件。为了解决这种warning的情况,只需将功能函数的原型拿出来,集体放到一个和main函数文件同名的.h文件中,在主文件中引用一下即可解决
demo1.h:
int Add(int a,int b);
int Mul(int a,int b);
原程序:
int Add(int a,int b){
return a+b;
}
int Mul(int a,int b){
return a*b;
}
#include <stdio.h>
#include "demo1.h"//添加此头文件
int main(){
int first,second,result;
printf("请输入第一个数:\n");
scanf("%d",&first);
printf("请输入第二个数:\n");
scanf("%d",&second);
printf("加法结果:%d\n",Add(first,second));
printf("乘法结果:%d\n",Mul(first,second));
return 0;
}