216

Can anyone explain why following code won't compile? At least on g++ 4.2.4.

And more interesting, why it will compile when I cast MEMBER to int?

#include <vector>

class Foo {  
public:  
    static const int MEMBER = 1;  
};

int main(){  
    vector<int> v;  
    v.push_back( Foo::MEMBER );       // undefined reference to `Foo::MEMBER'
    v.push_back( (int) Foo::MEMBER ); // OK  
    return 0;
}
codeling
  • 11,056
  • 4
  • 42
  • 71
Pawel Piatkowski
  • 2,359
  • 3
  • 15
  • 8
  • 1
    I edited the question to indent the code by four spaces instead of using
     
    . This means the angle brackets aren't interpreted as HTML.
    – Steve Jessop Nov 07 '08 at 19:03
  • https://stackoverflow.com/questions/16284629/undefined-reference-to-static-variable-c You can refer to this question. – Aqeel Raza Oct 03 '18 at 00:18
  • Since C++17 there is no need for the extra definition, see [my answer](https://stackoverflow.com/a/66569786/7691729) below. – Quimby Mar 10 '21 at 17:23

9 Answers9

207

You need to actually define the static member somewhere (after the class definition). Try this:

class Foo { /* ... */ };

const int Foo::MEMBER;

int main() { /* ... */ }

That should get rid of the undefined reference.

Drew Hall
  • 28,429
  • 12
  • 61
  • 81
  • 3
    Good point, inline static const integer initialization creates a scoped integer constant which you can't take the address of, and vector takes a reference param. – Evan Teran Nov 07 '08 at 18:08
  • 14
    This answer only addresses the first part of the question. The second part is much more interesting: Why does adding a NOP cast make it work without requiring the external declaration? – Brent Bradburn Feb 01 '11 at 00:48
  • 36
    I just spent a good bit of time figuring out that if the class definition is in a header file, then the allocation of the static variable should be in the implementation file, not the header. – shanet Jul 14 '12 at 03:06
  • 1
    @shanet: Very good point--I should have mentioned that in my answer! – Drew Hall Jul 14 '12 at 03:10
  • But if I declare it as const, is it not possible for me to change the value of that variable? – Namratha Nov 27 '12 at 04:57
  • @Namratha: Yup, that's the idea. – Drew Hall Nov 28 '12 at 04:13
  • @shanet: Actually, it depends. The example does show that excplicitly, but if class is a templated class or not fully specialized, then in the implementation file. Otherwise templated classes or partially specialized classes "enforces" location in the header file. – Andry May 03 '18 at 01:30
78

The problem comes because of an interesting clash of new C++ features and what you're trying to do. First, let's take a look at the push_back signature:

void push_back(const T&)

It's expecting a reference to an object of type T. Under the old system of initialization, such a member exists. For example, the following code compiles just fine:

#include <vector>

class Foo {
public:
    static const int MEMBER;
};

const int Foo::MEMBER = 1; 

int main(){
    std::vector<int> v;
    v.push_back( Foo::MEMBER );       // undefined reference to `Foo::MEMBER'
    v.push_back( (int) Foo::MEMBER ); // OK  
    return 0;
}

This is because there is an actual object somewhere that has that value stored in it. If, however, you switch to the new method of specifying static const members, like you have above, Foo::MEMBER is no longer an object. It is a constant, somewhat akin to:

#define MEMBER 1

But without the headaches of a preprocessor macro (and with type safety). That means that the vector, which is expecting a reference, can't get one.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Douglas Mayle
  • 21,063
  • 9
  • 42
  • 57
  • 2
    thanks, that helped... that could qualify for http://stackoverflow.com/questions/1995113/strangest-language-feature if it isn't there already... – Andre Holzner Dec 03 '10 at 13:45
  • 1
    Also worth noting that MSVC accepts the non-cast version without complaints. – porges Jun 26 '12 at 23:49
  • 4
    -1: This is simply not true. You're still supposed to define static members initialised inline, when they are _odr-used_ somewhere. That compiler optimisations may get rid of your linker error doesn't change that. In this case your lvalue-to-rvalue conversion (thanks to the `(int)` cast) occurs in the translation unit with perfect visibility of the constant, and the `Foo::MEMBER` is no longer _odr-used_. This is in contrast with the first function call, where a reference is passed around and evaluated elsewhere. – Lightness Races in Orbit Oct 06 '14 at 22:12
  • What about `void push_back( const T& value );`? `const&`'s can bind with rvalues. – Kostas Feb 24 '20 at 21:38
62

The C++ standard requires a definition for your static const member if the definition is somehow needed.

The definition is required, for example if it's address is used. push_back takes its parameter by const reference, and so strictly the compiler needs the address of your member and you need to define it in the namespace.

When you explicitly cast the constant, you're creating a temporary and it's this temporary which is bound to the reference (under special rules in the standard).

This is a really interesting case, and I actually think it's worth raising an issue so that the std be changed to have the same behaviour for your constant member!

Although, in a weird kind of way this could be seen as a legitimate use of the unary '+' operator. Basically the result of the unary + is an rvalue and so the rules for binding of rvalues to const references apply and we don't use the address of our static const member:

v.push_back( +Foo::MEMBER );
Richard Corden
  • 21,389
  • 8
  • 58
  • 85
  • 5
    +1. Yes it's certainly weird that for an object x of type T, the expression "(T) x" can be used to bind a const ref while plain "x" can't. I love your observation about "unary +"! Who would have thought that poor little "unary +" actually had a use... :) – j_random_hacker May 29 '09 at 10:38
  • 4
    Thinking about the general case... Is there any other type of object in C++ that has the property that it (1) can be used as an lvalue only if it has been defined but (2) can be converted to an rvalue without being defined? – j_random_hacker May 29 '09 at 10:51
  • Good question, and at least at the moment I cannot think of any other examples. This is probably only here because the committee were mostly just reusing existing syntax. – Richard Corden May 29 '09 at 12:47
  • @RichardCorden : how does the unary + resolved that ? – Blood-HaZaRd Jun 28 '18 at 15:10
  • 1
    @Blood-HaZaRd: Before rvalue references the only overload of `push_back` was a `const &`. Using the member directly resulted in the member being bound to the reference, which required it had an address. However, adding the `+` creates a temporary with the value of the member. The reference then binds to that temporary rather than requiring the member have an address. – Richard Corden Jul 13 '18 at 10:48
10

Aaa.h

class Aaa {

protected:

    static Aaa *defaultAaa;

};

Aaa.cpp

// You must define an actual variable in your program for the static members of the classes

static Aaa *Aaa::defaultAaa;
ollo
  • 24,797
  • 14
  • 106
  • 155
iso9660
  • 159
  • 2
  • 9
7

In C++17, there is an easier solution using inline variables:

struct Foo{
    inline static int member;
};

This is a definition of member, not just its declaration. Similar to inline functions, multiple identical definitions in different translation units do not violate ODR. There is no longer any need to pick a favourite .cpp file for the definition.

Quimby
  • 17,735
  • 4
  • 35
  • 55
2

Just some additional info:

C++ allows to "define" const static types of integral and enumeration types as class members. But this is actually not a definition, just an "initializiation-marker"

You should still write a definition of your member outside of the class.

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Marc
  • 338
  • 2
  • 15
1

No idea why the cast works, but Foo::MEMBER isn't allocated until the first time Foo is loaded, and since you're never loading it, it's never allocated. If you had a reference to a Foo somewhere, it would probably work.

Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
1

With C++11, the above would be possible for basic types as

class Foo {
public:  
  static constexpr int MEMBER = 1;  
};

The constexpr part creates a static expression as opposed to a static variable - and that behaves just like an extremely simple inline method definition. The approach proved a bit wobbly with C-string constexprs inside template classes, though.

starturtle
  • 699
  • 8
  • 25
  • This turned out to be essential for me, because the "static const int MEMBER = 1;" is needed to use MEMBER in switches, whilst the external declaration is needed to use it in vectors, and you cannot have both at the same time. But the expression you give here *does* work for both, at least with my compiler. – Ben Farmer Sep 16 '19 at 15:33
  • @BenFarmer: This approach stops needing an out-of-class definition in C++17 (because it’s implicitly inline, as variables can be in that version). – Davis Herring Nov 21 '20 at 03:06
0

Regarding the second question: push_ref takes reference as a parameter, and you cannot have a reference to static const memeber of a class/struct. Once you call static_cast, a temporary variable is created. And a reference to this object can be passed, everything works just fine.

Or at least my colleague who resolved this said so.

Quarra
  • 2,527
  • 1
  • 19
  • 27