const static linking problem

S

Shuo Xiang

Greetings:

For the following code:

class foo
{
...
private:
static const int x=3;
}

void foo::bar()
{
int i=x;
}

---

When it is linked the linker always complains of "undefined reference to
`foo::x'", why?

Regards,

Shuo
 
S

Shuo Xiang

Andrey said:
Because you forgot to define object 'foo::x' in your program. The
declaration is present, but the definition is missing. Provide a
definition and everything should compile without a problem

class foo
{
...
private:
static const int x = 3;
};

const int foo::x;

void foo::bar()
{
int i = x;
}

Note, that the new (post TC1) version of C++ standard no longer requires
'foo::x' to be defined for this particular code to compile. But your
compiler seems to follow the requirements of the original C++ standard.

Greetings:

Thank you! It was very helpful.

Regards,

Shuo
 
A

Andrey Tarasevich

Shuo said:
...
For the following code:

class foo
{
...
private:
static const int x=3;
}

void foo::bar()
{
int i=x;
}

---

When it is linked the linker always complains of "undefined reference to
`foo::x'", why?
...

Because you forgot to define object 'foo::x' in your program. The
declaration is present, but the definition is missing. Provide a
definition and everything should compile without a problem

class foo
{
...
private:
static const int x = 3;
};

const int foo::x;

void foo::bar()
{
int i = x;
}

Note, that the new (post TC1) version of C++ standard no longer requires
'foo::x' to be defined for this particular code to compile. But your
compiler seems to follow the requirements of the original C++ standard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,184
Latest member
ZNOChrista

Latest Threads

Top