C #include sth依赖混淆

时间:2014-09-28 09:29:17

标签: c

我在main.c

中有以下代码
#include "config.h"
#include "util.h"

并在config.h

#include "util.h"

并且util.h

中有正常的功能

因为我已经将util.h包括两次,所以我认为它应该是错误的

但不幸的是,当我输入gcc main.c config.c util.c

时,它真是太棒了

为什么这是对的?

2 个答案:

答案 0 :(得分:1)

C标头通常有标头防护,可防止它们多次被包含在内。例如:

#include <stdio.h>
#include <stdio.h>  // multiple inclusion of stdio.h, that's fine

标题保护位于标题的顶部:

 #ifndef MYHEADER_H
 #define MYHEADER_H

 // content of the header file

 #endif MYHEADER_H

答案 1 :(得分:1)

它不应该导致错误

如果您有下一个文件:

inc.h,inc1.h和inc.h包含inc1.h和inc1.h包含inc.h,然后它导致错误

协议后的头文件中的

        #ifndef HEADER_NAME_H
        #defiene HEADER_NAME_H
        //body of header file
        #endif /*HEADER_NAME_H*/

其中HEADER_NAME_H是&#34; header_name.h&#34;文件名