reincluding header in implementation

后端 未结 3 1899
遇见更好的自我
遇见更好的自我 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 <string> 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 <string> in foo.cpp, because it's already included by foo.h.

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

    0 讨论(0)
  • 2021-01-05 11:27

    I would say it is, because otherwise your foo.cpp is relying on a detail of foo.h that may change. Obviously this is more of a problem with other .h files that aren't under your control, but I still do it for consistency sake.

    0 讨论(0)
  • 2021-01-05 11:29

    Personally I follow the (questionable) minimal inclusion practice: I only include what's needed for compilation to work.

    People telling to get a better compiler / machine quite make me laugh, in a way, the project I am working on daily is compiled in about 8 minutes (from scratch) on a quad-core (was about 1 hour before I scrapped down dependencies) and I find it too damn long. I certainly don't want any change to cause the whole thing to recompile, and therefore I am wary of any include.

    During development, I always feel like compilation time is wasted time. A bit might allow a break sure, but when you want to test something now, it's only frustrating to wait for the damn thing to finally be ready (especially if it just blows in your hand when testing and you realize you'll have to modify it again and re-compile again).

    Including things twice seems like a good way to forget to remove the include from the source when it's no longer need by the header (hurray for forward declaration), I don't see the point.

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