哪些类型的头文件不应该被多重包含保护?

What kinds of header files should not be protected against multiple inclusion?

我看了dcmtk的源码,在ofstdinc.h里找到了评论:

// this file is not and should not be protected against multiple inclusion

哪些类型的头文件不应该受到保护以防止多重包含?

您几乎总是想防止多重包含。你唯一不想这样做的情况是,如果你正在用 C 宏做一些花哨的事情,因此你想要有多个包含来获得你想要的代码生成(没有这个副手的例子)。

预处理器元编程。也就是说,将包含的文件用作执行某些任务的一种 compile-time 函数。函数的参数是宏。例如,您链接的文件有一个如下所示的部分:

// define INCLUDE_STACK to include "ofstack.h"
#ifdef INCLUDE_STACK
#include "dcmtk/ofstd/ofstack.h"
#endif

所以如果我想包含 "ofstack.h",我会这样做:

#define INCLUDE_STACK
#include "ofstdinc.h"
#undef INCLUDE_STACK

现在,想象一下,有人想使用 header 的这个特定部分:

// define INCLUDE_STRING to include "ofstring.h"
#ifdef INCLUDE_STRING
#include "dcmtk/ofstd/ofstring.h"
#endif

所以他们做了以下事情:

#define INCLUDE_STRING
#include "ofstdinc.h"
#undef INCLUDE_STRING

如果"ofstdinc.h"包含守卫,则不会包含。

一个示例是 header 文件,这些文件希望您定义宏。考虑 header m.h

M( foo, "foo" )
M( bar, "bar" )
M( baz, "baz" )

这可以用在其他一些 header 中,像这样:

#ifndef OTHER_H
#define OTHER_H

namespace other
{
    enum class my_enum
    {
#define M( k, v ) k,
#include "m.h"
#undef M
    };

    void register_my_enum();
}

#endif

在其他一些文件中(可能是实现):

#include "other.h"

namespace other
{
    template< typename E >
    void register_enum_string( E e, const char* s ) { ... }

    void register_my_enum()
    {
#define M( k, v ) register_enum_string( k, v );
#include "m.h"
#undef M
    }
}