reincluding header in implementation

后端 未结 3 1916
遇见更好的自我
遇见更好的自我 2021-01-05 11:16

suppose I have a header foo.h like this:

#ifndef FOO_H
#define FOO_H
#include 
#include \"non_standard_class.h\"

std::string foo(         


        
3条回答
  •  旧巷少年郎
    2021-01-05 11:18

    The practice I follow:

    • foo.h should directly include all headers its source code needs (i.e. #include if there is std::string in foo.h)
    • foo.cpp should directly include foo.h plus all other headers its own source code needs, except for those already directly included by foo.h

    Another formulation of this practice: in foo.*, include only those headers the source code needs. If a header is needed by only foo.cpp (but not by foo.h), then include it from foo.cpp, otherwise include it from foo.h.

    So, in your case, I wouldn't #include in foo.cpp, because it's already included by foo.h.

    Let's assume that string does an #include , and foo.h contains std::vector. In this case, I'd #include in foo.h, because its source code needs it – and it doesn't matter that string already includes it.

提交回复
热议问题