how to include header files more clearly in C++

前端 未结 3 1596
逝去的感伤
逝去的感伤 2020-12-21 18:08

In C++, I have some header files such as: Base.h, and some classes using Base.h:

//OtherBase1.h
#include \"Base.h\"
class OtherBase         


        
3条回答
  •  被撕碎了的回忆
    2020-12-21 18:20

    You should be using include guards in Base.h.

    An example:

    // Base.h
    #ifndef BASE_H
    #define BASE_H
    
    // Base.h contents...
    
    #endif // BASE_H
    

    This will prevent multiple-inclusion of Base.h, and you can use both OtherBase headers. The OtherBase headers could also use include guards.

    The constants themselves can also be useful for the conditional compilation of code based on the availability of the API defined in a certain header.

    Alternative: #pragma once

    Note that #pragma once can be used to accomplish the same thing, without some of the problems associated with user-created #define constants, e.g. name-collisions, and the minor annoyances of occasionally typing #ifdef instead of #ifndef, or neglecting to close the condition.

    #pragma once is usually available but include guards are always available. In fact you'll often see code of the form:

    // Base.h
    #pragma once
    
    #ifndef BASE_H
    #define BASE_H
    
    // Base.h contents...
    
    #endif // BASE_H
    

提交回复
热议问题