15.1 源文件
一个源文件必须包含名为 main 的函数,此函数作为程序的起点
15.2 头文件
使用 include 预处理指令可以将几个文件联系在一起
#include <stdio.h>
#include <string.h>
// 这是同级目录下的另一个文件
// 且这个文件不能包含 main 函数
// 注意自己编写的头文件只能用 "",而不能用 <>
#include "array.cpp"
int main()
{
printf("1");
}
引入文件可以实现共享
15.2.3 共享函数原型
如果一个函数 f(),在另一个文件中,而在其他文件中需要调用这个函数,但是在这之前需要在其他文件中声明,如果一个一个声明,假设需要在 50 个其他文件,则要为这一个函数声明 50 次,且不出错是很麻烦的事情。
最好的方式是,将所有要跨文件调用的函数的声明放到一个自定义头文件中,然后引入头文件即可。
// array.h
void f();
// array.cpp
#include <stdio.h>
void f()
{
printf("1111");
}
// 主函数文件
#include <stdio.h>
#include <string.h>
// 凡是自定义的文件都要用 " "
#include "array.h"
// 这是同级目录下的另一个文件
// 且这个文件不能包含 main 函数
#include "array.cpp"
int main()
{
f();
}
// 输出
1111
15.2.4 共享变量
如果一个变量需要共享我们要怎么做呢
// print.h
void print(int i);
// sharing.c
// 在这里定义所有的共享变量,编译器为它分配空间
int i;
// print.c
#include <stdio.h>
void print(int i)
{
printf("%d",i);
}
// 主函数文件
// 函数原型声明
#include "print.h"
#include "sharing.c"
#include "print.c"
int main()
{
// 使用 extern 表示 i 已经在其他地方被定义了
// 这里只需要引入,而不用为它分配空间
extern int i;
i = 5;
print(i);
return 0;
}
// 输出
5