Afficher un message
Vieux 15/10/2007, 04h56   #3
Jack Klein
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Question about Unnamed Namespace

On Mon, 15 Oct 2007 03:15:53 -0000, CrazyJohn
<gatesgates2005@gmail.com> wrote in comp.lang.c++:

> Hi guys,
>
> This is my first time posting question here, if I break any rules,
> please kindly point out. And I'm really glad to be a part of this
> community.
>
> Here is my question,
>
> Our lecturer told us that Unnamed Namespace is an alternative to
> Static Internal Variables, but he also said that Namespace has an
> "Open" nature. Then, what if we create an integer variable in an
> unnamed namespace in one file and then create another integer variable
> with the same name in the unnamed namespace in another file? Will this
> cause a naming conflict?


The C++ standard requires that the unnamed namespace for each
translation unit in a program be unique.

> -- file1.cpp --
> namespace
> {
> int chenchen;
> }
>
> -- file2.cpp --
> namespace
> {
> int chenchen;
> }


In the example you show above, file1.cpp and file2.cpp are separate
translation units, unless one of them uses the #include directive to
include the contents of the other.

> If there is a naming conflict, then Unnamed Namespace is not able to
> function exactly the same as Static Internal Variable does; If there
> is no conflict, then Unnamed Namespace doesn't have an "Open"
> nature......So, why the standard includes such a feature?.......


This is actually a reasonable question to ask here, although I would
correct your terminology.

If you have this in a C program or C++ program, in a file and outside
of any functions:

static int x;

....this is called "file scope" in C and "namespace scope" in C++. The
object 'x' has file or namespace scope and internal linkage.

In C++, some constructions, such as templates, require that some
symbols they use must have external linkage, not internal linkage.

static int x;

....has internal, not external, linkage, but:

namespace
{
int x;
}

....has external linkage.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
  Réponse avec citation
 
Page generated in 0,06451 seconds with 9 queries