From: Eric Pruneau on

"matt" <lists(a)givemefish.com> a �crit dans le message de news:
14f75a01-536a-41bd-9f28-699f87087098(a)t23g2000yqt.googlegroups.com...
> Hi all,
>
> I was reading in Bruce Eckel's Thinking in C++, 2nd Ed Vol1, Ch 8
> about extern and const. He states that:
>
> "To use const instead of #define, you must be able to place const
> definitions inside header files as you can with #define. This way, you
> can place the definition for a const in a single place and distribute
> it to translation units by including the header file. A const in C++
> defaults to internal linkage; that is, it is visible only within the
> file where it is defined and cannot be seen at link time by other
> translation units."
>
> However, I wrote a short test program in gcc 4.4.1 that defines a non-
> extern constant within a header file as:
>
> const double myConst = 3.14159;
>
> This header is included by another file, which then uses the value of
> myConst without problem. The fact that this is allowed seems to
> contradict the assertions made by Eckel.

The important thing here is translation unit...

A translation unit is the basic unit of compilation in C++. It consists of
the contents of a single source file, plus the contents of any header files
directly or indirectly included by it, minus those lines that were ignored
using conditional preprocessing statements.



> So, is gcc allowing this although it shouldn't? Or is Mr. Eckel's
> statement incorrect? Or have I misunderstood something?
>

Example:

-----file1.cpp----

#include "file1.h"

......

double twoPi = 2*myConst; // ok defined in file2.h which is in the same
translation unit


-----file1.h-----

#include "file2.h"

.....

-----file2.h-------

const double myConst = 3.14159;

.....



Eric Pruneau


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Daniel Krügler on
On 8 Mrz., 23:06, Daniel Kr�gler <daniel.krueg...(a)googlemail.com>
wrote:
> On 8 Mrz., 20:15, matt <li...(a)givemefish.com> wrote:
> External variables (including constants with external
> linkage) can only be defined once per program without
> violating the one-definition rule.

... unless they are provided inside an unnamed-namespace:

namespace {

int var;

}

Greetings from Bremen,

Daniel Kr�gler


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]