一·多元文件软件开发
1.函数声明与定义分离
函数的声明,需要给出函数头即可,就是函数的返回值类型,函数名称和参数列表。而函数声明分为两种形势先声明后定义还有就是直接运用,一般我们用第一种的比较多一点。
例如:
#include<stdio.h>
int GetMin(int a,int b);
unsigned int GetDiff(int a);//对两个函数的声明
const int std_value=100;//const标准值变量定义
int main(void)
{
int a,b;
scanf("%d%d",&a,&b);
printf("Min:%d\n",GetMin(a,b));
}
int GetMin(int a,int b)
{
return GetDiff(a)<=GetDiff(b)?a:b;
}
unsigned int GetDiff(int a)
{
int value=std_value-a;
return value>0?value:-value;
}
2.extern关键词:
在一个源文件中把被调用的函数声明为外部函数,其他源文件中进行定义,从而避免了直接包含c源文件带来的错误。
例如
该代码文件在MyMath.c的文件中
#include<stdio.h>
int GetMin(int a,int b);
unsigned int GetDiff(int a);//对两个函数的声明
const int std_value=100;//const标准值变量定义
int GetMin(int a,int b)
{
return GetDiff(a)<=GetDiff(b)?a:b;
}
unsigned int GetDiff(int a)
{
int value=std_value-a;
return value>0?value:-value;
}
可以用
#include"MyMath.c"
直接引用,也可以用
extern int GetMin(int a,int b);
关键字extern进行引用
3.编译预处理命令
#ifndef FILENAME_H
#define FILENAME_H
...;
#endif
避免其中的函数被多次声明
例如:
#include<stdio.h>
#include"MyMath.c"
int main(void)
{
int a,b;
scanf("%d%d",&a,&b);
printf("Min:%d\n",GetMin(a,b));
}
在MyMath.c文件里
#include<stdio.h>
int GetMin(int a,int b);
unsigned int GetDiff(int a);//对两个函数的声明
const int std_value=100;//const标准值变量定义
int GetMin(int a,int b)
{
return GetDiff(a)<=GetDiff(b)?a:b;
}
unsigned int GetDiff(int a)
{
int value=std_value-a;
return value>0?value:-value;
}
在MyMath.h文件中
#ifndef MYMATH_H_
#define MYMATH_H_
int GetMin(int a,int b);
#endif
4.静态变量与静态函数
为解决多人协同开发软件开发时为避免在不同的C源文件中出现相同名称的局部变量和全局变量,并且通过extern关键字的声明就可以直接引用另外一个C源文件定义的全局变量和局部函数。可以在声明及定义时给前面加上关键词static,将其定义为静态函数和静态全局变量。例如;
#include<stdio.h>
static int GetMin(int a,int b);
static unsigned int GetDiff(int a);//声明静态局部函数
static const int std_value=100;//声明静态局部变量
int GetMin(int a,int b)
{
return GetDiff(a)<=GetDiff(b)?a:b;
}
unsigned int GetDiff(int a)
{
int value=std_value-a;
return value>0?value:-value;
}
5.内联函数
为降低函数调用的时间开销,可以通过关键词inline在函数定义时将其定义为内联函数,编译器对此函数调用语句编译时,用函数实现代码去直接替换调用函数语句,而不是像普通函数那样生成新的函数调用代码。
例如:
#include<stdio.h>
int GetMin(int a,int b);
static unsigned int GetDiff(int a);//声明静态局部函数
static const int std_value=100;//声明静态局部变量
int GetMin(int a,int b)//定义外部函数
{
return GetDiff(a)<=GetDiff(b)?a:b;
}
inline static unsigned int GetDiff(int a)
{
int value=std_value-a;
return value>0?value:-value;
}
6.const变量与形参
为防止程序员在不经意间改变有些特殊的变量C语言提供了const关键字,除了定义变量以外,const还通常用来声明函数的指针类型的形参。
例如:
#include<stdio.h>
typedef struct
{
int ID;
char name[30];
int score;
}student_t;
void Print(const student_t *p);
int main(void)
{
student_t stu={1,"zhang san",100};
Print(&stu);
return 0;
}
void Print(const student_t *p)
{
printf("The data of the student are follows:\n");
printf("IG:%d\nName:%s\nScore:%d\n",p->ID,p->name,p->score);
}