之前我们写的代码,是放在一个.c文件中,如果main写在一个.c文件中,max()写在一个.c文件中呢?
把函数原型 放到一个 以.h结尾的头文件中,在需要调用这个函数的 .c 源代码文件中 #include这个头文件,编译器在编译的时候就知道函数的原型了
新建——源代码——max.h max.h
double max(double a,double b);max.c
#include "max.h"double max(double a,double b){ return a > b ? a : b;}main.c
#include <stdio.h>#include "max.h"int main(void) { double a = 5; double b = 6; PRintf("max is %f/n", max(5, 6)); // max is 6.000000 return 0;}错误示例:
struct Node{ int value; char* name;};// [Error] redefinition of 'struct Node' 重新定义 struct Node struct Node{ int value; char* name;};int main(void) { return 0;}标准写法: max.h
#ifndef _MAX_H_#define _MAX_H_ double max(double a,double b);extern int gAll;struct Node{ int value; char* name;};#endifmax.c
#include <stdio.h>#include "max.h"int gAll = 12;int main(void) { double a = 5; double b = 6; printf("max is %f/n", max(5, 6)); // max is 6.000000 return 0;}max.c
#include "max.h"double max(double a,double b){ return a > b ? a : b;}新闻热点
疑难解答