where should “include” be put in C++

后端 未结 9 1971
生来不讨喜
生来不讨喜 2020-12-14 16:06

I\'m reading some c++ code and Notice that there are "#include" both in the header files and .cpp files . I guess if I move all the "#include" in the fi

9条回答
  •  囚心锁ツ
    2020-12-14 16:13

    You can avoid multiple definition errors if you use "include guards".

    (begin myheader.h)
    #ifndef _myheader_h_
    #define _myheader_h_
    struct blah {};
    extern int whatsit;
    #endif //_myheader_h_
    

    Now if you #include "myheader.h" in other header files, it'll only get included once (due to _myheader_h_ being defined). I believe MSVC has a "#pragma once" with the equivalent functionality.

提交回复
热议问题