473,626 Members | 3,183 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about anonymous namespace...

I am reading the book "C++ Annotations", and here is a quote from the
book:

Namespaces can be defined without a name. Such a namespace is
anonymous and it restricts the
visibility of the defined entities to the source file in which the
anonymous namespace is defined.
Entities defined in the anonymous namespace are comparable to C’s
static functions and variables.
In C++ the static keyword can still be used, but its use is more
common in class definitions
(see chapter 6). In situations where static variables or functions are
necessary, the use of the
anonymous namespace is preferred.
--------------

Could anybody give me an example about why the anonymous name space is
the same as "static" variables and functions in C?

thanks!
Oct 22 '08 #1
22 3908
Luna Moon wrote:
I am reading the book "C++ Annotations", and here is a quote from the
book:

Namespaces can be defined without a name. Such a namespace is
anonymous and it restricts the
visibility of the defined entities to the source file in which the
anonymous namespace is defined.
Entities defined in the anonymous namespace are comparable to C’s
static functions and variables.
In C++ the static keyword can still be used, but its use is more
common in class definitions
(see chapter 6). In situations where static variables or functions are
necessary, the use of the
anonymous namespace is preferred.
--------------

Could anybody give me an example about why the anonymous name space is
the same as "static" variables and functions in C?
The quote says it all: "it restricts the visibility of the defined
entities to the source file in which the anonymous namespace is defined"

Which is exactly what "static" does in C.

--
Ian Collins
Oct 22 '08 #2
In article
<4b************ *************** *******@a29g200 0pra.googlegrou ps.com>, Luna
Moon <lu**********@g mail.comwrote:
I am reading the book "C++ Annotations", and here is a quote from the
book:

Namespaces can be defined without a name. Such a namespace is
anonymous and it restricts the visibility of the defined entities
to the source file in which the anonymous namespace is defined.
Entities defined in the anonymous namespace are comparable to C's
static functions and variables. In C++ the static keyword can still
be used, but its use is more common in class definitions (see
chapter 6). In situations where static variables or functions are
necessary, the use of the anonymous namespace is preferred.

--------------

Could anybody give me an example about why the anonymous name space is
the same as "static" variables and functions in C?
Why? Because the standard says so. Actually, the effect is not exactly the same.

// Before namespace
static int i;
static void f() { }
struct my_foo { };

// After namespace
namespace
{
int i;
void f() { }
struct foo { }; // no need for prefix on name, since it's now a local name
}

BTW, the proper term is "unnamed namespace" (C++03 7.3.1.1). The author of
the C++ book you're reading should have taken the time to get it right.
Oct 23 '08 #3
On Oct 23, 9:08 am, blargg....@gish puppy.com (blargg) wrote:
In article
<4b97d33c-17f1-4bf8-a02b-71ca05250...@a2 9g2000pra.googl egroups.com>,
Luna Moon <lunamoonm...@g mail.comwrote:
[...]
Could anybody give me an example about why the anonymous
name space is the same as "static" variables and functions
in C?
Why? Because the standard says so. Actually, the effect is not
exactly the same.
// Before namespace
static int i;
static void f() { }
struct my_foo { };
// After namespace
namespace
{
int i;
void f() { }
struct foo { }; // no need for prefix on name, since it's now a localname
}
Another important difference is the linkage of the name. A
static variable or function has internal linkage. A name in an
anonymous namespace has external linkage---the reason it can't
be seen from other translation units is that it isn't namable in
them. (Formally, it is visible everywhere, but since it can't
be named, there's no way to actually see it.) A template can
only be instantiated over something that has external linkage,
e.g.:

template< int* p class T {} ;

static int i ;
namespace {
int j ;
}

T< &i ti ; // illegal...
T< &j tj ; // legal.
BTW, the proper term is "unnamed namespace" (C++03 7.3.1.1).
The author of the C++ book you're reading should have taken
the time to get it right.
The term anonymous namespace seems pretty widespread to me.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 23 '08 #4
... A template can only be instantiated over something that
has external linkage, e.g.:

template< int* p class T {} ;

static int i ;
namespace {
int j ;
}

T< &i ti ; // illegal...
T< &j tj ; // legal.
To me, anonymous namespaces were just the C++ way of saying static.
The external linkage point is new to me. But:

Pointer-to-int as template argument? Instantiating templates over
something with external linkage? Could you provide a practical example
working with anonymous namespace but not working with static? Note
that you could also omit the static keyword to the same effect.
BTW, the proper term is "unnamed namespace" (C++03 7.3.1.1).
The author of the C++ book you're reading should have taken
the time to get it right.

The term anonymous namespace seems pretty widespread to me.
I'd bet a horse and a carrot that "unnamed" is the literal meaning of
"anonymous" .

Best regards,
Andreas.
Oct 23 '08 #5
On Oct 23, 3:08*am, blargg....@gish puppy.com (blargg) wrote:

[snip]
// Before namespace
static int i;
static void f() { }
struct my_foo { };

// After namespace
namespace
{
* * int i;
* * void f() { }
* * struct foo { }; // no need for prefix on name, since it's now a local name

}

Now I'm curious. Take the following code from the same compilation
unit:

namespace
{
int i;
void x() { }
}

namespace
{
int j;
void y() { }
}

Would i be visible to y(), and j be visible to x()?
Oct 23 '08 #6
On 2008-10-23 12:23:54 -0400, Michael Mol <mi*****@gmail. comsaid:
On Oct 23, 3:08Â*am, blargg....@gish puppy.com (blargg) wrote:

[snip]
>// Before namespace
static int i;
static void f() { }
struct my_foo { };

// After namespace
namespace
{
Â* Â* int i;
Â* Â* void f() { }
Â* Â* struct foo { }; // no need for prefix on name, since it's now a l
ocal name
>>
}


Now I'm curious. Take the following code from the same compilation
unit:

namespace
{
int i;
void x() { }
}

namespace
{
int j;
void y() { }
}

Would i be visible to y(),
yes.
and j be visible to x()?
no.

Same answer with a named namespace and without a namespace.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Oct 23 '08 #7
Now I'm curious. Take the following code from the same compilation
unit:

namespace
{
int i;
void x() { }
}

namespace
{
int j;
void y() { }
}

Would i be visible to y(), and j be visible to x()?
Generally, namespaces can be split across several compilation units.
The only exception to this rule are anonymous namespaces. If you would
split an anonymous namespace across several compilation units, it
wouldn't be the same namespace. That's because anonymous namespaces
are not truely anonymous, it's just that their name is not accessible
by the coder. The compiler, however, assigns a unique ID to them per
compilation unit.

But, as you're asking for the same compilation unit, yes, i is visible
to y(), and no, j is not visible to x().

Best regards,
Andreas.
Oct 23 '08 #8
In article
<34************ *************** *******@g61g200 0hsf.googlegrou ps.com>,
Michael Mol <mi*****@gmail. comwrote:
On Oct 23, 3:08 am, blargg....@gish puppy.com (blargg) wrote:

[snip]
// Before namespace
static int i;
static void f() { }
struct my_foo { };

// After namespace
namespace
{
int i;
void f() { }
struct foo { }; // no need for prefix on name, since it's now a
// local name

}

Now I'm curious. Take the following code from the same compilation
unit:

namespace
{
int i;
void x() { }
}

namespace
{
int j;
void y() { }
}

Would i be visible to y(), and j be visible to x()?
Heck, since we're talking about the same translation unit, you could also add

// at file scope in same translation unit
void z()
{
i = 0;
j = 0;
x();
y();
}

and it would see everything in your unnamed namespaces (and z would be
visible to other translation units).
Oct 23 '08 #9
On Oct 23, 5:35*pm, "spamboun...@gm x.de" <spamboun...@gm x.dewrote:
... A template can only be instantiated over something that
has external linkage, e.g.:
* * template< int* p class T {} ;
* * static int i ;
* * namespace {
* * * * int j ;
* * }
* * T< &i ti ; * // *illegal...
* * T< &j tj ; * // *legal.
To me, anonymous namespaces were just the C++ way of saying
static. The external linkage point is new to me. But:
Pointer-to-int as template argument?
Why not? It was the simplest example that came to my mind.
Instantiating templates over something with external linkage?
Anything you use to instantiate a template must have external
linkage. Those are the rules.
Could you provide a practical example working with anonymous
namespace but not working with static?
I just did. See above: declare the variable static, and you
can't use it to instantiate the template. Define it in an
anonymous namespace, and you can.

I run into this a lot because of const; const is static by
default, so something like:

template< int* p class T{} ;

namespace {
int const i = 43 ;
}

T< &i t ; // illegal.

You have to define the int:
extern int const i = 43 ;

(In practice, of course, most of the time, it's a user defined
class, and the template parameter is a reference, rather than a
pointer, and it's a function template, not a class template.
But the same principles apply.)
Note that you could also omit the static keyword to the same
effect.
Except that if I omitted the static keyword in my example, the
symbol would be visible in every module. And conflict with
another module which did exactly the same thing with the same
name.
BTW, the proper term is "unnamed namespace" (C++03 7.3.1.1).
The author of the C++ book you're reading should have taken
the time to get it right.
The term anonymous namespace seems pretty widespread to me.
I'd bet a horse and a carrot that "unnamed" is the literal
meaning of "anonymous" .
Actually, no. From the way I understand English, anonymous
means that the name is hidden, and not visible; unnamed means
that it doesn't exist. In which case, anonymous is actually
closer to what really happens.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 23 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
5863
by: Jason Heyes | last post by:
I wrote: namespace { void f(); } void f() { std::cout << "hello world" << std::endl; } When I compile, I receive this error: unresolved external symbol "bool __cdecl `anonymous namespace'::f(void)" What have I done wrong? Thanks.
3
7792
by: Frederick Gotham | last post by:
Back in the day, if you wanted a function to be self-contained within a translation unit, you defined the function as "static". If there were an external linkage function by the same name residing in a different translation unit, then the current translation unit was simply oblivious to it and had no way of accessing it. Any time the function name was mentioned in the current translation unit, it referred to the "static" one which...
1
1801
by: wenmang | last post by:
Hi, I try to use variables declared in anonymous namespace as file scope vars. But, during the debugging effort, those variables are not visible to debugger, how can I access those vars? thx
12
5398
by: Taras_96 | last post by:
Hi everyone, AFAIK external linkage allows you to refer to variables/functions outside of the current translation unit. A variable in an unnamed namespace is similar to declaring a static variable, but according to the standard there is a difference: "While this is essentially true in practical effect, there are subtle differences. Using static as shown here causes "i" to have internal
5
3891
by: gauravbjain | last post by:
I am planning to move from ‘static’ keyword to anonymous namespace for variables/functions which are local to a translation unit. This is to move code closer to C++, since static for file level names is deprecated by standard. I am queries if doing this may have any downside associated with it, since it would give external linkage to all these names? May be size increase of generated object files which I believe should be taken care by...
3
3428
by: Al Grant | last post by:
Consider two translation units, (1): namespace { struct S { }; } struct D: S { virtual int f(void); }; and (2): #include <typeinfo> struct D; char const *f(D *p) { return typeid(p).name(); }
0
8265
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8705
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8637
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4092
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4197
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2625
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1511
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.