Re: Where to "include"
On Nov 10, 6:27 pm, Andrea Crotti <andrea.crott...@gmail.com> wrote:
Supposing I have a file
A.hpp:
#include <iostream>
// various defintions using ostream
A.cpp:
#include "A.hpp"
// again definitions the functions + other stuff
Should I still include iostream or since it's in the A.hpp is really not
needed?
In smaller projects, where A.hpp and A.cpp are maintained as
a unit, always by the same person, it's not necessary. In
larger projects, where A.hpp is maintained as part of an
external interface, I'd add the include, since it might
disappear from A.hpp later. And of course, I'd never count on
any of the includes in any of the other headers.
And while I'm at it: only in the most exceptional cases should
A.hpp (or A.cpp, for that matter) include <iostream>. Usually,
A.hpp will only include <iosfwd>, and A.cpp will only include
the headers it actually needs, typically <istream> and/or
<ostream>. The header <iostream> is generally only used in
small, quicky programs, or in modules which set up the IO (and
thus might have to know about std::cin and std::cout).
And the headers only needed in the "cpp" files should be included only
there right?
And what's the best syntax for the guard?
Actually I just use
#ifndef GLOBALS_H
#define GLOBALS_H
but maybe it's name clashing dangerous, so a better question would be
which names to avoid? (Would the compiler notice that?)
The best practice today (at least in the Unix world) is to
append a number of random characters at the end, to ensure
uniqueness, e.g. Array_hh_20072809DQkZRhAIaTRgrRaykaYwqBol.
This is, of course, generated automatically when you open a new
..hpp in your editor. Doing this means that the Lakos policy of
wrapping the #include statements themselves with the guard can't
be used (since you can't know the guard outside of the header),
which in turn means that you don't want to use it on large
projects using VC++, because VC++ doesn't know how to avoid
multiple inclusions otherwise. (Perhaps throwing in a #pragma
once would help. I've not experimented with it.)
Alternatively, something like <subsystem>_<filename> seems to
work well (converted to all caps or not) for complete programs,
with all non alphanums converted to _. Libraries should add
some sort of explicit prefix as well.
--
James Kanze