简体   繁体   English

圆形包含C中的头文件

[英]Round include of header files in C

is it possible to make something like round include in C? 是否有可能在C中制作圆形包含 example: in ial.h - #include "adt.h" and in adt.h - #include "ial.h"

This is called a circular dependency , and while it's possible, you should not . 这被称为循环依赖 ,虽然它是可能的,但你不应该这样做 Avoid designing around the concept at all costs. 避免不惜一切代价围绕这个概念设计。

What you should do is extract the common ground from both headers and create a third one, that both include . 你应该做的是从两个标题中提取共同点并创建第三个标题,两者都include

   bad         good

a <---> b     a     b
              |     |
              -> c <-

If you find you can't do this, then most likely a and b are the same semantic unit, and belong in the same header. 如果您发现无法执行此操作,则很可能ab是相同的语义单元,并且属于同一标头。

Obviously, if you did that, and didn't do anything else, you'd have an infinitely long file as the circular dependency kept including its components. 显然,如果你这样做,并且没有做任何其他事情,那么你将拥有一个无限长的文件,因为循环依赖包括其组件。

But lots of people include lots of files in C, so this sort of thing is bound to happen. 但很多人在C中包含大量文件,所以这种事情必定会发生。

Enter include guards . 输入包括警卫 In each (well-designed) header file, there must be a way to make sure that you break the circular dependency. 在每个(设计良好的)头文件中,必须有一种方法来确保您打破循环依赖。 The two most popular ways use different precompiler macros: 两种最常用的方法使用不同的预编译器宏:

#pragma once for compilers that accept this (which is now most of them), it makes sure that the header is only included once per compilation. #pragma once用于接受它的编译器(现在大部分都是这样),它确保每个编译只包含一次头。 Put it at the top of each header, and you're ok. 把它放在每个标题的顶部,你没事。

ifdefs - something like this ifdefs - 像这样的东西

#if !defined(__MY_HEADER_H__)
#define __MY_HEADER_H__
/* all the code */
#endif

You'll see include guards on any standard header. 您会在任何标准标题上看到包含警戒。

I do like uʍop ǝpısdn's answer, though - if it's your code, do everything you can to avoid creating this kind of dependency. 我确实喜欢uʍopǝpısdn的答案 - 如果这是你的代码,尽你所能避免创造这种依赖。

I guess you should be able to do it by using #ifndef : 我想你应该可以使用#ifndef来做到这一点:

In ial.h : ial.h

#ifndef IAL_H
#define IAL_H

...

#include "adt.h"

...

#endif

In adt.h : adt.h

#ifndef ADT_H
#define ADT_H

...

#include "ial.h"

...

#endif

Whether it is a good idea or not, I would say don't do it. 无论是否是个好主意,我都会说不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM