## Recommended Posts

CDProp    1451
Hello. I wanted to avoid using #include inside any of my header files, so that I can avoid dependency problems. I was under the impression that I could simply include all the headers I need in the corresponding .cpp file as long as the #include lines for those files appeared before I include the .h file in question. For instance, suppose that I had Foo.h and Foo.cpp, and the header file has perhaps some STL vectors in it. I was under the impression that, instead of including <vector> in the .h file, I could include it in the .cpp file as long as the #include <vector> line appears before the #include Foo.h line, like this: #include <vector> #include Foo.h However, when I try this with my program, it doesn't work. I get "missing type specifier" errors. What am I doing wrong?

##### Share on other sites
Sneftel    1788
Quote:
 Original post by CDPropI wanted to avoid using #include inside any of my header files, so that I can avoid dependency problems. I was under the impression that I could simply include all the headers I need in the corresponding .cpp file as long as the #include lines for those files appeared before I include the .h file in question.

##### Share on other sites
CDProp    1451
Regardless, is my assumption about how the preprocessor directive works incorrect?

Edit: Thank you.

##### Share on other sites
Sneftel    1788
Quote:
 Original post by CDPropRegardless, is my assumption about how the preprocessor directive works incorrect?

##### Share on other sites
smitty1276    560
You're correct. Whenever the preprocessor encounters "#include <whatever>", it simply dumps the contents of whatever into that position.

So your example is exactly equivalent to simply including vector at the top of foo.h, except, of course, for style... a header should take care of its own dependencies.

##### Share on other sites
CDProp    1451
Ok, I've taken them out. :P

I wonder why the compiler was confused about what a std::vector was, though, when I included <vector> in the source file before including the corresponding header.

*shrug*

Edit: I just realized that the header file was included in another source file that didn't have those includes it depended on before it. The other source file was likely compiled first, thus demonstrating your point. ROFL.

##### Share on other sites
JohnBolton    1372
An effective way to reduce header file dependencies in C++ is to use forward declarations. If a class is referenced in a header file via a pointer or reference or as a return value, then it is likely that you can use a forward declaration instead of including the header file. A forward declaration works something like this:
    class Foo; // forward declaration    class Bar    {        Foo GetFoo();        void SetFoo( Foo & foo );    };