Why it's valid to include a header file twice in c++?

后端 未结 7 879
迷失自我
迷失自我 2021-02-09 17:25
#include \"DLLDefines.h\"
#include \"DLLDefines.h\"

The above actually passed compilation, but why?

相关标签:
7条回答
  • 2021-02-09 18:21

    include has nothing to do with the C or C++ language. It is a directive to the preprocessor to bring in a file. The preprocessor doesn't care what file is brought in and it shouldn't. It might be perfectly acceptable to do this:

    void Foo::SomeFunc(int cond)
    {
        switch (cond) {
        case kThisCase:
    #include "longFirstCase.h"
            break;
        case kSecondCase:
    #include "longSecondCase.h"
            break;
        case kThirdCase:
    #include "longFirstCase.h"
    #include "longSecondCase.h"
            break;
        }
    }
    

    I have seen the same file included several times as a configuration mechanism as well.

    Granted, there are a number of ways to factor that example that are better, but the point is that there may be perfectly good reasons why you would want to and therefore no restriction on the use.

    0 讨论(0)
提交回复
热议问题