15.1 源文件

一个源文件必须包含名为 main 的函数,此函数作为程序的起点

15.2 头文件

使用 include 预处理指令可以将几个文件联系在一起

  1. #include <stdio.h>
  2. #include <string.h>
  3. // 这是同级目录下的另一个文件
  4. // 且这个文件不能包含 main 函数
  5. // 注意自己编写的头文件只能用 "",而不能用 <>
  6. #include "array.cpp"
  7. int main()
  8. {
  9. printf("1");
  10. }

引入文件可以实现共享
image.png

15.2.3 共享函数原型

如果一个函数 f(),在另一个文件中,而在其他文件中需要调用这个函数,但是在这之前需要在其他文件中声明,如果一个一个声明,假设需要在 50 个其他文件,则要为这一个函数声明 50 次,且不出错是很麻烦的事情。

最好的方式是,将所有要跨文件调用的函数的声明放到一个自定义头文件中,然后引入头文件即可。

  1. // array.h
  2. void f();
  3. // array.cpp
  4. #include <stdio.h>
  5. void f()
  6. {
  7. printf("1111");
  8. }
  9. // 主函数文件
  10. #include <stdio.h>
  11. #include <string.h>
  12. // 凡是自定义的文件都要用 " "
  13. #include "array.h"
  14. // 这是同级目录下的另一个文件
  15. // 且这个文件不能包含 main 函数
  16. #include "array.cpp"
  17. int main()
  18. {
  19. f();
  20. }
  21. // 输出
  22. 1111

15.2.4 共享变量

如果一个变量需要共享我们要怎么做呢

  1. // print.h
  2. void print(int i);
  3. // sharing.c
  4. // 在这里定义所有的共享变量,编译器为它分配空间
  5. int i;
  6. // print.c
  7. #include <stdio.h>
  8. void print(int i)
  9. {
  10. printf("%d",i);
  11. }
  12. // 主函数文件
  13. // 函数原型声明
  14. #include "print.h"
  15. #include "sharing.c"
  16. #include "print.c"
  17. int main()
  18. {
  19. // 使用 extern 表示 i 已经在其他地方被定义了
  20. // 这里只需要引入,而不用为它分配空间
  21. extern int i;
  22. i = 5;
  23. print(i);
  24. return 0;
  25. }
  26. // 输出
  27. 5