Where to "include"

A

Andrea Crotti

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?
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?)
 
S

Saeed Amrollahi

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?
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?)

Hi
I use the following experiences/practices:
1. I ensure each header file be a self-sufficient.
2. I ensure each corresponding pair header and source files are
compiled separately.
So, in response to 1st question, I just include <iostream> in a
header file.
In most cases, if the code for <iostream> removes from header file,
the code
for <iostream> in source file is redundant too.
3. I try to make Include Guard using file-name. As we know, the file-
names in a directory
are unique, So the name clash is really rare.
I definitely don't use the underscore (_) in the beginning of
include guards,
it is a bad practice. I usually, use rather long include guards.
4. About include guards, I usually have two problems:
- Mostly, I copy/paste the content of a header file in a newer
another header file
and I forget to change the the guards appropriately.
- Sometimes, I forget to guard the include file content, so I get
multiple definition error.
I'm sure, others have own good practices and coding styles.

Regards,
-- Saeed Amrollahi
 
V

Victor Bazarov

Supposing I have a file
A.hpp:
#include<iostream>

// various defintions using ostream

If you need to use 'std::eek:stream', include <ostream> and not <iostream>.
Familiarize yourself what those headers are to define and use them for
the proper stuff. Do not rely on the fact that on your implementation
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?

If in A.hpp it's not needed, don't include it.

You should include anything that is needed for the compilation of that
particular translation unit. What happens often is that if you don't
include <something> explicitly [again], and somebody edits 'A.hpp' to
And the headers only needed in the "cpp" files should be included only
there right?

Only include those headers that are needed. If you're talking about a
header (although those aren't to be compiled by themselves), think of
compiling a translation unit that only contains the inclusion directive
with your header. Should not cause any compiler errors.
And what's the best syntax for the guard?
Actually I just use
#ifndef GLOBALS_H
#define GLOBALS_H

If this is inside the file called "Globals.h", I'd probably use the name
'HEADER_Globals_H_INCLUDED'. Don't be afraid of the long names, you
only get to type them once (use copy-paste for the #define).
but maybe it's name clashing dangerous, so a better question would be
which names to avoid? (Would the compiler notice that?)

The names to avoid: starting with 'E', starting with an underscore and a
capital letter, containing two consecutive underscores (those are
reserved by the implementation).

V
 
J

James Kanze

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.
 
H

Helge Kruse

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.)

Your assumption is correct. The (compiler specific) #pragma makes these
guards absolete, as long as you stay in the VC++ environment. When you plan
to share the includes with projects that use other compilers, the guards are
necessary.

BTW, some version of VC++ created automatically a guard based on a GUID what
can be compared with your random characters.

Helge
 
D

DeMarcus

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?)

If you use namespaces, which you should, then don't forget to put that
in the name. E.g.

#ifndef SPACENAMESPACE_MOONLANDER_HPP_
#define SPACENAMESPACE_MOONLANDER_HPP_

namespace SpaceNamespace
{

class Moonlander
{
// ...
};


} // namespace SpaceNamespace

#endif


I also saw someone putting the project name in the guard, like this

#ifndef APOLLO_SPACENAMESPACE_MOONLANDER_HPP_
#define APOLLO_SPACENAMESPACE_MOONLANDER_HPP_


/Daniel
 
A

Andrea Crotti

DeMarcus said:
If you use namespaces, which you should, then don't forget to put that
in the name. E.g.

#ifndef SPACENAMESPACE_MOONLANDER_HPP_
#define SPACENAMESPACE_MOONLANDER_HPP_

namespace SpaceNamespace
{

class Moonlander
{
// ...
};


} // namespace SpaceNamespace

#endif


I also saw someone putting the project name in the guard, like this

#ifndef APOLLO_SPACENAMESPACE_MOONLANDER_HPP_
#define APOLLO_SPACENAMESPACE_MOONLANDER_HPP_


/Daniel

Well my project makes sense to be in only one namespace since I'm using
classes everywhere, I only use one namespace where I have global
variables not already encapsulated.

For me it doesn't make a big difference to write very long strings for
the guard (since emacs does it automatically), but I just don't see much
the reason..

I mean unless I'm so stupid to choose something used by my compiler then
it should be someone else using my code guards to cause the problem,
right?

But wouldn't he get a compiler error immediately after?
I mean what are the probabilities to get something anyway working even
if I actually don't include a neeeded header??
 
R

Ruslan Mullakhmetov

The names to avoid: starting with 'E', starting with an underscore and a
capital letter, containing two consecutive underscores (those are
reserved by the implementation).

i'm just wondering why is it dangerous to use guards starting with 'E'?
 
V

Victor Bazarov

i'm just wondering why is it dangerous to use guards starting with 'E'?

The whole point of reserving a name for the implementation is to prevent
possible name clashes and inadvertent altering of the meaning of the
code without changing the code itself. Danger is that the code might
not mean what the programmer intended it to mean.

V
 
G

Gennaro Prota

On 12/11/2010 17.25, Pete Becker wrote: [...] {NOTE: I wrapped the lines of the following paragraph as I
kept getting an NNTP error when I left it in its original line
length}
Good point. C99 (and, if I remember correctly, C90) says
"Macros that begin with E and a digit or E and an uppercase
letter may be added to the declarations in the <errno.h>
header."

There are a lot of reserved names (that programmers don't know
about). Some are reserved unconditionally (not necessarily for
any use), for instance, in C, those starting with underscore +
uppercase letter, but also names such as "toto", "isgood" or
"strike"; others are reserved when a given header is included,
e.g. SIG (or SIG_) + uppercase letter (when <signal.h> is
included).

C, C++ and POSIX all add to the list. In practice in C++ there's
not much difference between the two categories because you don't
know what headers are really included from whatever place, even
if that's in your code.

Yet another case, IMHO, of the language working against the
programmer.
 
J

James Kanze

On 12/11/2010 17.25, Pete Becker wrote: [...]

[...]
There are a lot of reserved names (that programmers don't know
about). Some are reserved unconditionally (not necessarily for
any use), for instance, in C, those starting with underscore +
uppercase letter, but also names such as "toto", "isgood" or
"strike"; others are reserved when a given header is included,
e.g. SIG (or SIG_) + uppercase letter (when <signal.h> is
included).
C, C++ and POSIX all add to the list. In practice in C++ there's
not much difference between the two categories because you don't
know what headers are really included from whatever place, even
if that's in your code.

You do know that a C++ header will not include a Posix header.
(And vice versa, I think, since Posix headers have to be
acceptable to a C compiler.)
Yet another case, IMHO, of the language working against the
programmer.

It's at least partially linked to the use of include by the
preprocessor, rather than true support for modules.
 
M

Marc

James said:
You do know that a C++ header will not include a Posix header.
(And vice versa, I think, since Posix headers have to be
acceptable to a C compiler.)

Uh?
I assume that by posix you mean those posix headers that are not C
headers and similarly for C++ you exclude *.h and c*.
C++ headers can (and do, on unix systems) include posix headers. New
C++0X features like threads will make that even more obvious.
As for the reverse direction, it is indeed probably rare, but I don't
think it is forbidden.
 
J

James Kanze


The C standard specifies exactly and completely all of the names
that each header defines; a conformant implementation cannot
define any others in the header (except in the reserved
namespace, i.e. names starting with a _).

C++ allows any standard header to include any other, so you may
get more names than those defined in the header you include.
But still limited to names defined by the standard in one of the
standard headers (or names in the reserved namespace, of
course).
I assume that by posix you mean those posix headers that are not C
headers and similarly for C++ you exclude *.h and c*.

No. I mean all Posix headers. Except, of course, those names
that are common to both C and Posix: if you include <stdio.h>,
you get printf, and on an X/Open system, a printf with the
X/Open extensions (which is still standard C, since the X/Open
extensions define what is otherwise undefined behavior).

There are a very few incompatibilities between some of the Posix
headers and the C standard. Posix recognizes this, and
(IIRC) specifies that by default you get standard C; you have to
explicitly define a preprocessor symbol to get Posix. And even
then you only get these few incompatibilities; you don't pull in
any other Posix headers.
C++ headers can (and do, on unix systems) include posix headers.

If they do, it's a very, very poor implementation. There's no
reason to.
New
C++0X features like threads will make that even more obvious.
Why?

As for the reverse direction, it is indeed probably rare, but
I don't think it is forbidden.

I don't think Posix forbids including other Posix and C headers.
Like C and C++, however, it does forbid introducing additional
symbols, not defined in Posix (or C, since Posix includes the C
standard by reference), in a Posix header.

Note that the guarantees given by the C and the C++ standards go
even further: if your code contains symbols which are defined by
Posix, and you don't include Posix headers, your code must link
correctly, and use your code, e.g.:

#include <stdio.h>

int
read(int fd, char* buf, size_t len)
{
puts(buf);
}

int
main()
{
static char hello[]= "hello, world!";
read(0, hello, 0);
char ch = getchar();
return 0;
}

must compile, link and output "hello, world!" when executed.
(Back in the 1980's, it didn't always. But that was then; I
can't imagine a system today where this didn't work.)
 
H

Helge Kruse

Victor Bazarov said:
The whole point of reserving a name for the implementation is to prevent
possible name clashes and inadvertent altering of the meaning of the code
without changing the code itself. Danger is that the code might not mean
what the programmer intended it to mean.

I'm just wondering, what is the special danger of guards starting with 'E'?

Helge
 
B

Bart van Ingen Schenau

I'm just wondering, what is the special danger of guards starting with 'E'?

The danger is that your header will not get included.
For example:

//file: efile.h
#ifndef EFILE
#define EFILE

extern int x;

#endif

//file: impl.cpp
#include <errno.h> // defines EFILE
#include "efile.h"

void foo()
{
x = 1; // Error: identifier 'x' undeclared
}

Bart v Ingen Schenau
 
G

Gennaro Prota

On 12/11/2010 17.25, Pete Becker wrote: [...]
[...]
Good point. C99 (and, if I remember correctly, C90) says
"Macros that begin with E and a digit or E and an uppercase
letter may be added to the declarations in the <errno.h>
header."
There are a lot of reserved names (that programmers don't know
about). Some are reserved unconditionally (not necessarily for
any use), for instance, in C, those starting with underscore +
uppercase letter, but also names such as "toto", "isgood" or
"strike"; others are reserved when a given header is included,
e.g. SIG (or SIG_) + uppercase letter (when <signal.h> is
included).
C, C++ and POSIX all add to the list. In practice in C++ there's
not much difference between the two categories because you don't
know what headers are really included from whatever place, even
if that's in your code.

You do know that a C++ header will not include a Posix header.
(And vice versa, I think, since Posix headers have to be
acceptable to a C compiler.)
Yet another case, IMHO, of the language working against the
programmer.

It's at least partially linked to the use of include by the
preprocessor, rather than true support for modules.

Yes, but only in part. The problem IMHO is that too many common
names are reserved "lightheartedly", with the easy escape (for
the committee) that using them is undefined behavior.

What can the programmer really do? If you have a C++ program
using POSIX headers (if just by linking to a library that does)
can you check that it doesn't define any reserved identifier?

<http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html>
 
E

Ebenezer

Euh... what about filenames in different directories?
What about two files in the same directory that differ only by
capitalisation  (I know, not possible on all OS and not necessarily
good pratice but exists, for example in the linux kernel source code)

Use the filename as part of header guards but for safety and sanity,
also use something else like a sufficiently large random number, a
guid, a timestamp or the module name too.


I favor intentional names so am fine with using module names for
this purpose. I wouldn't use an editor to generate a bunch of
junk characters. Adding junk to a file is not acceptable in my
view. Something I have to be on guard against is generating too
much code simply because it isn't difficult. I can imagine a
timestamp being useful in some cases.

Brian Wood
Ebenezer Enterprises
http://webEbenezer.net
http://wnd.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,709
Latest member
AustinMudi

Latest Threads

Top