什么类型的头文件不应该被保护以防止多个包含?

sfz*_*sfz 15 c c++ multiple-inclusions

我读了dcmtk源代码,并在ofstdinc.h中找到了注释:

// this file is not and should not be protected against multiple inclusion
Run Code Online (Sandbox Code Playgroud)

什么样的头文件不应该被保护免受多重包含?

Ben*_*ley 12

预处理器元编程.也就是说,使用包含的文件作为执行某些任务的编译时函数.该函数的参数是宏.例如,您链接的文件有一个如下所示的部分:

// define INCLUDE_STACK to include "ofstack.h"
#ifdef INCLUDE_STACK
#include "dcmtk/ofstd/ofstack.h"
#endif
Run Code Online (Sandbox Code Playgroud)

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

#define INCLUDE_STACK
#include "ofstdinc.h"
#undef INCLUDE_STACK
Run Code Online (Sandbox Code Playgroud)

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

// define INCLUDE_STRING to include "ofstring.h"
#ifdef INCLUDE_STRING
#include "dcmtk/ofstd/ofstring.h"
#endif
Run Code Online (Sandbox Code Playgroud)

所以他们做了以下事情:

#define INCLUDE_STRING
#include "ofstdinc.h"
#undef INCLUDE_STRING
Run Code Online (Sandbox Code Playgroud)

如果"ofstdinc.h"包含警卫,则不包括在内.


Dan*_*rey 12

一个例子是头文件,它们希望你定义一个宏.考虑一个头m.h

M( foo, "foo" )
M( bar, "bar" )
M( baz, "baz" )
Run Code Online (Sandbox Code Playgroud)

这可以在其他一些标题中使用,如下所示:

#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
Run Code Online (Sandbox Code Playgroud)

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

#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
    }
}
Run Code Online (Sandbox Code Playgroud)