在多重继承的情况下避免包含守卫

问题描述 投票:0回答:1

我在C程序中有一个继承结构如下:

program.c 包括 support.h 和 utility.h
support.h 包括 core.h
utility.h 包括 core.h

由于 core.h 包括枚举和 typedef,它们在 program.c 中发生冲突。支持和实用程序都使用依赖于 core.h 中的 typedef 的原型

有没有什么方法可以避免使用 include guards?

我读过理论观点,即 include 文件不应该在其中包含其他内容 这当然可以解决我的问题。但我不明白如何避免这种情况。如果我在头文件中的

prune( TREES* t );
中有像
gardening.h
这样的原型,并且typedef
TREES
位于不同的头文件
tree.h
中,我真的不知道如何避免在
中包含
tree.h
 gardening.h

c include
1个回答
1
投票

您可以通过在

"core.h"
和/或
"utility.h"
之前包含
"support.h"
并且不在其中任何一个包含文件中包含
"core.h"
来解决不包含守卫的程序。

这是整个项目必须遵循的约定,但是需要程序员在每个源文件中解决所有的include文件依赖关系,这对于大型项目来说是繁琐且容易出错的。当依赖项随着新版本的定义而改变时,这将成为维护的噩梦,尤其是当编译器错误消息关于从哪里获取缺少的定义时不太明显。

program.c:

#include <stdbool.h>  // needed by core.h, utility.h
#include <stdio.h>    // needed by utility.h
#include <stdlib.h>   // needed by support.h

#include "core.h"     // needed by support.h, utility.h
#include "support.h"
#include "utility.h"
...

support.c:

#include <stdbool.h>  // needed by core.h
#include <stdlib.h>   // needed by support.h

#include "core.h"     // needed by support.h
#include "support.h"
...

utility.c:

#include <stdbool.h>  // needed by core.h, utility.h
#include <stdio.h>    // needed by utility.h

#include "core.h"     // needed by utility.h
#include "utility.h"
...

我建议遵循不同的约定:确保所有文件都包含所需定义所需的任何包含文件,包括应编译为空目标文件的包含文件本身,这样更简单也更可靠。防止多重包含产生冗余定义的错误是通过使用项目范围的约定来避免名称冲突的包含保护来完成的。

现代编译器针对此约定进行了优化,并跳过已经解析过的包含文件,这些文件的内容受定义的包含保护保护。

© www.soinside.com 2019 - 2024. All rights reserved.