作业帮 > C/C++ > 教育资讯

C语言教程:头文件避免重复包含

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/27 18:12:03 C/C++
C语言教程:头文件避免重复包含
C语言教程:头文件避免重复包含C/C++
【无忧考网 - C/C++】
假定有以下几个头文件及其包含关系为:

  File1.h,file2.h,file3.h,file4.h,file5.h,main.cpp

  那么:file3.h包含file1.h,file2.h,file4.h包含file1.h,file2.h,file5.h包含file3.h,file4.h。如许就会导致在file5中对file1和file2的反复包含,编译时就会报错。

  解决方法:

  1:应用#ifndef

  #define

  #endif

  即每个文件在定义时都写成以下情势(以file1.h为例):

  #ifndefH_FILE1

  #defineH_FILE1

  #include

  #include

  …..

  #endif

  File3.h:#ifndefH_FILE3

  #defineH_FILE3

  #include

  #include

  #inlcude”file1.h”

  #include”file2.h”

  …..

  #endif

  方法二:在每个文件的头部定义:#pragmaonce(用于解释本文件中的内容只应用一次)

  例:fiel1.h:

  #pragmaonce

  #include

  #include

  …..

  File3.h:

  #pragmaonce

  #include

  #include

  #include”file1.h”

  …..

C/C++