473,791 Members | 3,122 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Static member and namespace - a puzzle.

Either I have found a puzzle, or I am just being stupid. Inside a
namespace I have a class with a static const double member. The
member is not an int so I cannot initialise it within the class, I
have to initialise it outside the class. The problem is that when I
tried putting the initialisation in the header file immediately after
the class my compiler (g++) rejected it, citing "multiple definition":

g++.exe alphaMain.o alpha.o -o "Alpha.exe" -L"C:/DEV-CPP/lib"
alpha.o(.text+0 x0):alpha.cpp: multiple definition of
`foo::AlphaC::m _doubl'
alphaMain.o(.te xt+0x0):alphaMa in.cpp: first defined here

Then I tried moving the initialisation outside the namespace, but
still in the header file. Same error. Finally I put the
initialisation at the end of the .cpp file, outside the namespace
again. That seemed to work and compiled with no errors.

Another aspect to the puzzle is that when I concatenate the three
files: alpha.h, alpha.cpp and alphaMain.cpp into a single file then it
compiles normally with the initialisation where I first put it, after
the class and inside the namespace.

I can't see that I am doing anything stupid, can another pair of eyes
see my error?
rossum
(Getting ready to say "Doh!" and bang my head on the keyboard.)

// alpha.h -----------------------

#ifndef ALPHA_H_INCLUDE
#define ALPHA_H_INCLUDE

namespace foo {

class AlphaC {
private:
static const double m_doubl;
int m_data;

public:
AlphaC() : m_data(0) {}

void increment();
}; // end class AlphaC

// const double AlphaC::m_doubl = 1.0; // This doesn't work,
// but it does work if the 3 files are combined into one.

} // end namespace foo

// const double foo::AlphaC::m_ doubl = 1.0; // This doesn't work

#endif // ALPHA_H_INCLUDE

// alpha.cpp ---------------------

#include "alpha.h"

namespace foo {

void AlphaC::increme nt() {
++m_data;
} // end increment()

} // end namespace foo

const double foo::AlphaC::m_ doubl = 1.0; // This works. Why?
// alphaMain.cpp -----------------

#include "alpha.h"

int main() {
foo::AlphaC my_alpha;

my_alpha.increm ent();

return 0;

} // end main()

--

The ultimate truth is that there is no Ultimate Truth
Jul 22 '05 #1
5 2049
"rossum" <ro******@coldm ail.com> wrote...
Either I have found a puzzle, or I am just being stupid. Inside a
namespace I have a class with a static const double member. The
member is not an int so I cannot initialise it within the class, I
have to initialise it outside the class. The problem is that when I
tried putting the initialisation in the header file immediately after
the class my compiler (g++) rejected it, citing "multiple definition":
[...]
Pull the definition out of the header. Imagine that instead of writing
'#include "alpha.h"' in your source files you simply stuff the contents
of that header into those source files (that's what the pre-processor
essentially does). How many modules contain your definition now? So,
why are you surprised?
Then I tried moving the initialisation outside the namespace, but
still in the header file. Same error. Finally I put the
initialisation at the end of the .cpp file, outside the namespace
again. That seemed to work and compiled with no errors.

Another aspect to the puzzle is that when I concatenate the three
files: alpha.h, alpha.cpp and alphaMain.cpp into a single file then it
compiles normally with the initialisation where I first put it, after
the class and inside the namespace.
Well, how many translation units are there when you concatenate the
three files? How many definitions of the static data member?

I can't see that I am doing anything stupid, can another pair of eyes
see my error?


Do you really need an extra pair of eyes for that? I think you need
a better book.

V
Jul 22 '05 #2
> Either I have found a puzzle, or I am just being stupid. Inside a
namespace I have a class with a static const double member. The
member is not an int so I cannot initialise it within the class, I
have to initialise it outside the class. The problem is that when I
tried putting the initialisation in the header file immediately after
the class my compiler (g++) rejected it, citing "multiple definition":
That's quite normal, because if you include the header twice, the member
gets defined twice, and that's illegal.
g++.exe alphaMain.o alpha.o -o "Alpha.exe" -L"C:/DEV-CPP/lib"
alpha.o(.text+0 x0):alpha.cpp: multiple definition of
`foo::AlphaC::m _doubl'
alpha.cpp : that's one.
alphaMain.o(.te xt+0x0):alphaMa in.cpp: first defined here
alphaMain.cpp : that' two.
Another aspect to the puzzle is that when I concatenate the three
files: alpha.h, alpha.cpp and alphaMain.cpp into a single file then it
compiles normally with the initialisation where I first put it, after
the class and inside the namespace.


Because you end up with only one file.

The ODR (One Definition Rule) states that you can only have one
definition for all names (with some exceptions). So

int main()
{
int a;
int a; // violates ODR
}

And

// in my_header.h
int a;

// in 1.cpp
# include <my_header.h> // first definition

// in 2.cpp
# include <my_header.h> // second, bang you're dead.
The usual way to work with statics initialization is to do it in the
impl file :

// c.h
class C
{
static int my_int;
};

// c.cpp
int C::my_int = 3;

So my_int is initialized in one place only.
Jonathan
Jul 22 '05 #3
On Tue, 23 Nov 2004 23:34:12 GMT, "Victor Bazarov"
<v.********@com Acast.net> wrote:

Thanks for the replies Jonathan and Victor,
"rossum" <ro******@coldm ail.com> wrote...
Either I have found a puzzle, or I am just being stupid. Inside a
namespace I have a class with a static const double member. The
member is not an int so I cannot initialise it within the class, I
have to initialise it outside the class. The problem is that when I
tried putting the initialisation in the header file immediately after
the class my compiler (g++) rejected it, citing "multiple definition":
[...]
Pull the definition out of the header. Imagine that instead of writing
'#include "alpha.h"' in your source files you simply stuff the contents
of that header into those source files (that's what the pre-processor
essentially does). How many modules contain your definition now? So,
why are you surprised?

When I constructed the single file, I left both the #include<alpha. h>
lines in as well as the copy of the file, so that file included the
definition three times.

I put include guards in the header file to avoid the problem of
including things more than once, and they seem to have worked OK with
the single file.

I thought that the second time the header file was encountered it
would be ignored. Is it that the include guards only work across a
single compilation unit and do not work between different compilation
units? What is the lifetime of a given #define?

<bangs head on keyboard> hjm hgujc v

[snip]

I can't see that I am doing anything stupid, can another pair of eyes
see my error?


Do you really need an extra pair of eyes for that? I think you need
a better book.


No, but I may need to read it more thoroughly: TC++PL (3rd edition).
rossum

V

--

The ultimate truth is that there is no Ultimate Truth
Jul 22 '05 #4
rossum wrote:
On Tue, 23 Nov 2004 23:34:12 GMT, "Victor Bazarov"
<v.********@com Acast.net> wrote:
"rossum" <ro******@coldm ail.com> wrote...
Either I have found a puzzle, or I am just being stupid. Inside a
namespace I have a class with a static const double member. The
member is not an int so I cannot initialise it within the class, I
have to initialise it outside the class. The problem is that when I
tried putting the initialisation in the header file immediately after
the class my compiler (g++) rejected it, citing "multiple definition":
[...]


Pull the definition out of the header. Imagine that instead of writing
'#include "alpha.h"' in your source files you simply stuff the contents
of that header into those source files (that's what the pre-processor
essentially does). How many modules contain your definition now? So,
why are you surprised?


When I constructed the single file, I left both the #include<alpha. h>
lines in as well as the copy of the file, so that file included the
definition three times.

I put include guards in the header file to avoid the problem of
including things more than once, and they seem to have worked OK with
the single file.

Something like

# include "alpha.h" // first definition

// alpha.h stuff manually copied here
// second definition

// the rest of the file

Where's that third definition? And that should not have compiled if a
name is defined twice (once in the header and once in the copied lines).
I thought that the second time the header file was encountered it
would be ignored.
The language does not mandate that, that's why we use include guards.
Is it that the include guards only work across a
single compilation unit and do not work between different compilation
units?
Yes.
What is the lifetime of a given #define?


A translation unit.
Jonathan
Jul 22 '05 #5
On Tue, 23 Nov 2004 21:32:45 -0500, Jonathan Mcdougall
<jo************ ***@DELyahoo.ca > wrote:

[snip]
Is it that the include guards only work across a
single compilation unit and do not work between different compilation
units?
Yes.
What is the lifetime of a given #define?


A translation unit.


Yes, I worked that out while trying to get to sleep. I had got into
the habit of thinking of defines as "global" so I got stuck on the
idea that they survived across translation units. Thinking about it
(rather than assuming) made it clear that they do not.

Thanks for your help, the dialogue helped me to see things more
clearly.

Doh!

gbfc ,kij

Doh!

gjf,jmf gfjvbf

Doh!

f,jvj,fgjm j

rossum


Jonathan


--

The ultimate truth is that there is no Ultimate Truth
Jul 22 '05 #6

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

Similar topics

29
4413
by: Alexander Mahr | last post by:
Dear Newsgroup, I'm somehow confused with the usage of the static keyword. I can see two function of the keyword static in conjunction with a data member of a class. 1. The data member reffers in all objects of this class to the same data Or in other word by using the static keyword all objects of one class can share data. (This is what I want)
8
4594
by: Scott J. McCaughrin | last post by:
The following program compiles fine but elicits this message from the linker: "undefined reference to VarArray::funct" and thus fails. It seems to behave as if the static data-member: VarArray::funct were an extern, but it is declared in the same file (q.v.). What is the remedy for this? =================
4
4897
by: Serge | last post by:
Hi, I have no problem creating a static member variable with integers, etc but when I try the same with a vector then I always get linker errors that the static member variable is unknown (unresolved external symbol) Below is what an example of the code I use. Can somebody tell me what I am doing wrong ? Thanks very much in advance, Serge //myclass.h
3
4609
by: ishekara | last post by:
Hi, Can you solve the puzzle for me? I have a main.cpp, testinclude.h, and test1.cpp and test2.cpp which include testinclude.h testinclude.h has a class Include defined. I always thought that the compiler generates a copy of class Include one each for test1.cpp and test2.cpp. But however they use the same class definition for both test1.cpp and test2.cpp.
5
1654
by: SemSem | last post by:
when i was usong c++ idont have to put static before tha function that i want to acces but in c# i have to but it . ex : ihave a function called add(int x,int y) i have to put static int add(int x,int y) in prototype or i have this "an object refrence is required for the nonstatic field, methiod or property"
1
3094
by: wenqiang.zhou | last post by:
i only kown that static members doesnt blong to any object and it have to initialize outside class, inline is near the same as define it will replace in code.but i was puzze by the following codes. // the first example is the one i predigest from <<the c++ program language>> written by Bjarne Stroustrup #include <iostream> using namespace std; class Date
4
3514
by: Josefo | last post by:
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token vector_static_function.c:21: error: expected constructor, destructor, or type conversion before '.' token
1
2419
by: Visame | last post by:
The following example is from C++ Standard(ISO14882) 9.4.2 Static data members class process { static process* run_chain; static process* running; }; process* process::running = get_main();//what does get_main() mean here? process* process::run_chain = running; C++ Standard also says in:
15
7873
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
0
9666
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
9512
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
10419
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...
1
10147
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
9987
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9023
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
7531
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...
1
4100
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
3709
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.