strange link problem

A

arcimboldo

Hello,

I got a strange link problem; here are the simplest files showing the
error:

a.h::
#include <utility>

class a{
public:
typedef int perm;
static const perm PERM_NONE = 0;
a();
private:
std::pair<int, perm> aaa;
};

a.cpp::
#include "a.h"
a::a() : aaa(0,PERM_NONE) { }
main () { }

Compiling with g++ (GCC) 3.3.5 (Debian 1:3.3.5-13) I get::

$ g++ a.cpp
/tmp/ccKKUXg8.o: In function
`a::a[not-in-charge]()':a.cpp:(.text+0xa): undefined reference to
`a::pERM_NONE'
/tmp/ccKKUXg8.o: In function `a::a[in-charge]()':a.cpp:(.text+0x34):
undefined reference to `a::pERM_NONE'
collect2: ld returned 1 exit status

The file compiles correctly, the error shows up only when linking.

What could it possibly be? Thanks for any help!

Arcimboldo
 
M

marcwentink

What could it possibly be?

What if you delete the 'static' keyword?
What if you construct aaa not in the list but in the
compound statement "{}" of the constructor?

My guess is that the static var is not yet initialized when a::a() :
aaa(0,PERM_NONE) { } is called.

Marc Wentink
 
D

Dietmar Kuehl

The problem is because static data members need to be defined exactly
once in every translation unit.

Nope! Static data members have to be defined exactly once in the
whole program. The only exception are constant integral expressions
whose address is never taken: these don't need any definition.
However, addresses are easily taken, e.g. by passing the value to a
function taking an 'int const&' as parameter. The best bet for a
constant integral expression which does not need a separate
definition is using an enum.
 
F

Fei Liu

Hello,

I got a strange link problem; here are the simplest files showing the
error:

a.h::
#include <utility>

class a{
public:
typedef int perm;
static const perm PERM_NONE = 0;
a();
private:
std::pair<int, perm> aaa;
};

a.cpp::
#include "a.h"
a::a() : aaa(0,PERM_NONE) { }
try a::a(): aaa(0, a::pERM_NONE){}
main () { }

Compiling with g++ (GCC) 3.3.5 (Debian 1:3.3.5-13) I get::

$ g++ a.cpp
/tmp/ccKKUXg8.o: In function
`a::a[not-in-charge]()':a.cpp:(.text+0xa): undefined reference to
`a::pERM_NONE'
/tmp/ccKKUXg8.o: In function `a::a[in-charge]()':a.cpp:(.text+0x34):
undefined reference to `a::pERM_NONE'
collect2: ld returned 1 exit status

The file compiles correctly, the error shows up only when linking.

What could it possibly be? Thanks for any help!

Arcimboldo
 

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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top