473,809 Members | 2,940 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

non static variables in a namespace (in .h) ?

Hi,

Sorry for the bad subject, but i couldn't figure a better one.

I would like to understand why a variable declared non static in a
header causes multiple symbol definitions (if included in different
compilation units) while the same declaration in a namespace does not.

Also, what is the correct way to declare a scoped variable in a
header ? Using extern and declaring it in a separate compilation
unit ?

Thank you,
Vincent

Mar 7 '07 #1
9 2772
vt********@gmai l.com wrote:
Hi,

Sorry for the bad subject, but i couldn't figure a better one.

I would like to understand why a variable declared non static in a
header causes multiple symbol definitions (if included in different
compilation units) while the same declaration in a namespace does not.
Could you show me an example, cause if you define a variable twice in
the same namespace, you should get multiple symbol definitions and
linker errors.

Did you mean you can define the same variable in different namespaces?
That's fine, of course.
>
Also, what is the correct way to declare a scoped variable in a
header ? Using extern and declaring it in a separate compilation
unit ?
If you have to put the definition in a namespace in a header included in
multiple compilation units, then you should declare it extern and define
it in a single compilation unit.

ex:

myhdr.hh

#ifndef MYHDR_HH_
#define MYHDR_HH_

namespace myns {
extern int myvar;
}

#endif

main.cc

#include "myhdr.hh"

int myns::myvar;

int main() {
myns::myvar = 6;
}

aux.cc

#include "myhdr.hh"

void myfcn() {
myns::myvar = 10;
}

--John Ratliff
Mar 7 '07 #2
vt********@gmai l.com wrote:
Sorry for the bad subject, but i couldn't figure a better one.

I would like to understand why a variable declared non static in a
header causes multiple symbol definitions (if included in different
compilation units) while the same declaration in a namespace does not.
I don't believe that the second part of this statement is correct.
Are you sure about "the same declaration"?

Anyway, an object that is not const and is not explicitly declared
'static' has _external_ linkage, IOW its name is visible from other
translation units. If you define (if the declaration does not have
'extern' specifier, it's a definition) objects with the same name
in more than one translation unit, it's a violation of the ODR. You
usually get the error from the linker who is the last to check the
ODR when linking different TUs together.

If you declare the object 'static', its name is hidden from other TU
(not extern), the term is that the name has _internal_ linkage. That
way you can have objects named the same in different TUs.
Also, what is the correct way to declare a scoped variable in a
header ?
"Scoped"? What does that mean? Any variable is scoped, IOW every
variable has its scope.
Using extern and declaring it in a separate compilation
unit ?
There are variations on the theme, but they all essentially lead to
the same: declaration is available in every TU, and the definition
exist only in one TU.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 7 '07 #3
John Ratliff wrote:
vt********@gmai l.com wrote:
>Hi,

Sorry for the bad subject, but i couldn't figure a better one.

I would like to understand why a variable declared non static in a
header causes multiple symbol definitions (if included in different
compilation units) while the same declaration in a namespace does
not.

Could you show me an example, cause if you define a variable twice in
the same namespace, you should get multiple symbol definitions and
linker errors.

Did you mean you can define the same variable in different namespaces?
That's fine, of course.
I just thought of what it could be: anonymous namespaces. But that
falls under "different" category, of course, only the OP didn't think
of it that way, most likely.
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 7 '07 #4
On 7 mar, 19:49, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
vthomas...@gmai l.com wrote:
I would like to understand why a variable declared non static in a
header causes multiple symbol definitions (if included in different
compilation units) while the same declaration in a namespace does not.

I don't believe that the second part of this statement is correct.
Are you sure about "the same declaration"?
My example comes from some software i use. In the main include file,
it declares a
bunch of strings as in the following:

namespace x {
const std::string s1 = "txt1";
const std::string s2 = "txt2";
}

and the software compiles and runs just fine. When i saw this it
struck as being strange (that it didn't cause link time error), so i
just added a simple test string declaration outside of the namespace
and, of course, got a bunch of 'redeclared symbol' messages at link
time.
Anyway, an object that is not const and is not explicitly declared
'static' has _external_ linkage, IOW its name is visible from other
translation units. If you define (if the declaration does not have
'extern' specifier, it's a definition) objects with the same name
in more than one translation unit, it's a violation of the ODR. You
usually get the error from the linker who is the last to check the
ODR when linking different TUs together.
These strings are const. Does it make any difference ?
"Scoped"? What does that mean? Any variable is scoped, IOW every
variable has its scope.
I meant in a namespace... sorry.
There are variations on the theme, but they all essentially lead to
the same: declaration is available in every TU, and the definition
exist only in one TU.
OK, so being in a namespace does not change the linkage type in any
way ?

Vincent

Mar 7 '07 #5
On 7 mar, 19:48, John Ratliff <u...@example.n etwrote:
vthomas...@gmai l.com wrote:
Could you show me an example, cause if you define a variable twice in
the same namespace, you should get multiple symbol definitions and
linker errors.
See my response to Victor Bazarow. I can give a link to the header
file on source control if you would like to see the real code, but
it's really as plain as i said (though the variables are const).
Did you mean you can define the same variable in different namespaces?
That's fine, of course.
No, i meant in the same namespace.
If you have to put the definition in a namespace in a header included in
multiple compilation units, then you should declare it extern and define
it in a single compilation unit.
<snip example code>

OK, this is how i understand it, so i don't understand why it works
correctly in this other software.

Vincent

Mar 7 '07 #6
vt********@gmai l.com wrote:
On 7 mar, 19:49, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
>vthomas...@gma il.com wrote:
>>I would like to understand why a variable declared non static in a
header causes multiple symbol definitions (if included in different
compilation units) while the same declaration in a namespace does
not.

I don't believe that the second part of this statement is correct.
Are you sure about "the same declaration"?

My example comes from some software i use. In the main include file,
it declares a
bunch of strings as in the following:

namespace x {
const std::string s1 = "txt1";
const std::string s2 = "txt2";
}
So, have you tried doing the same without the namespace? Does it
make an iota of difference (except for the s1 and s2 name lookup)?
and the software compiles and runs just fine. When i saw this it
struck as being strange (that it didn't cause link time error), so i
just added a simple test string declaration outside of the namespace
and, of course, got a bunch of 'redeclared symbol' messages at link
time.
Nothing strange. Objects are 'const', they have internal linkage.
>
>Anyway, an object that is not const and is not explicitly declared
'static' has _external_ linkage, IOW its name is visible from other
translation units. If you define (if the declaration does not have
'extern' specifier, it's a definition) objects with the same name
in more than one translation unit, it's a violation of the ODR. You
usually get the error from the linker who is the last to check the
ODR when linking different TUs together.

These strings are const. Does it make any difference ?
Absodamnlutely.
>"Scoped"? What does that mean? Any variable is scoped, IOW every
variable has its scope.

I meant in a namespace... sorry.
Well, those that are "not in a namespace" are actually *in* the
_global_ namespace. The prefix for finding those is '::'. E.g.

int a = 0;
int main() {
double a = 3.14159;
return ::a; // note the ::
}

There are two 'a' objects here, one has global namespace scope,
the other has 'main' function scope.
>There are variations on the theme, but they all essentially lead to
the same: declaration is available in every TU, and the definition
exist only in one TU.

OK, so being in a namespace does not change the linkage type in any
way ?
Nope.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 7 '07 #7
On 7 mar, 20:18, vthomas...@gmai l.com wrote:
and the software compiles and runs just fine. When i saw this it
struck as being strange (that it didn't cause link time error), so i
just added a simple test string declaration outside of the namespace
and, of course, got a bunch of 'redeclared symbol' messages at link
time.
Hmmm, sorry, i just realized that i declared a non const string
outside
the namespace (which caused the error). If declared const, i don't get
a linking error, so it appears my question is actually about the const
keyword rather than on being in a namespace.

Mar 7 '07 #8
vt********@gmai l.com wrote:
On 7 mar, 20:18, vthomas...@gmai l.com wrote:
>and the software compiles and runs just fine. When i saw this it
struck as being strange (that it didn't cause link time error), so i
just added a simple test string declaration outside of the namespace
and, of course, got a bunch of 'redeclared symbol' messages at link
time.

Hmmm, sorry, i just realized that i declared a non const string
outside
the namespace (which caused the error). If declared const, i don't get
a linking error, so it appears my question is actually about the const
keyword rather than on being in a namespace.
Yep. 'const' without "extern" gives the object internal linkage.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 7 '07 #9
On 7 mar, 20:47, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
vthomas...@gmai l.com wrote:
namespace x {
const std::string s1 = "txt1";
const std::string s2 = "txt2";
}

So, have you tried doing the same without the namespace? Does it
make an iota of difference (except for the s1 and s2 name lookup)?
I have now. :-)
Nothing strange. Objects are 'const', they have internal linkage.
Thanks a lot for your explanations.

Vincent
Mar 7 '07 #10

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

Similar topics

4
8037
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned in "Learning Python" by Mark Lutz and David Ascher. It seems like they are a relatively new feature... It seems to me that any truly OO programming language should support these so I'm sure that Python is no exception, but how can these be...
6
3166
by: pembed2003 | last post by:
Hi all, I am reading the book "C++ How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope function-prototype scope I think(might be wrong):
16
2989
by: Eric | last post by:
I have a static class member variable as follows: struct A { static void Set (int i) { v = i; } static int& Get () { return v; } static int v; }; int A::v; // define A::v in the cpp file
2
3590
by: Drew McCormack | last post by:
I am getting an error in g++ 4.0.0 that I did not get in g++ 3.4. I have a header with the following const variables with namespace scope: namespace Periphery { extern const double ProtonMassInAtomicUnits = 1836.152755656068; } I try to use these in another header to initialize static const member
3
7377
by: Sehcra | last post by:
Hi, I'm trying to figure out if what I'm doing makes any sense. I created a namespace that contains some functions as well as some constants. Because these variables are constant, I have no need for there to be more than one copy of them. Does it make sense to make these variables static const, or do I just make them const? If this were a class instead of a namespace, I would obviously want to make the variables static, but this kind...
9
6370
by: Bryan Parkoff | last post by:
I have noticed that C programmers put static keyword beside global variable and global functions in C source codes. I believe that it is not necessary and it is not the practice in C++. Static keyword is useful inside struct, class, and function only unless you want to force local variable to be global variable so static is used. Do you have idea why most programmers do this? Bryan Parkoff
1
3539
by: Sandro Bosio | last post by:
Hello everybody, my first message on this forum. I tried to solve my issue by reading other similar posts, but I didn't succeed. And forgive me if this mail is so long. I'm trying to achieve the following (with incomplete succes): I want in a given namespace Parameters a list of "initializers" (which are objects derived from a simple interface that can be implemented anywhere, and are used to define which parameters the program will take at...
3
5862
by: Steve Folly | last post by:
Hi, I had a problem in my code recently which turned out to be the 'the "static initialization order fiasco"' problem (<http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12>) The FAQ section describes a solution using methods returning references to static objects. But consider:
14
6032
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared static inside functions (i.e. local static objects) 5. objects declared at file scope.
15
2971
by: kj | last post by:
Yet another noob question... Is there a way to mimic C's static variables in Python? Or something like it? The idea is to equip a given function with a set of constants that belong only to it, so as not to clutter the global namespace with variables that are not needed elsewhere. For example, in Perl one can define a function foo like this *foo = do {
0
9722
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
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10643
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
10378
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...
1
10391
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9200
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...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3862
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
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.