Undefined Reference to Static Variable C++

Undefined reference to static variable

You only declared A::i, need to define A::i before using it.

class A  
{
public:
static int i;
static void init(){
i = 1;
}
};

int A::i = 0;

int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
A::i = 0;
A::init();

return 0;
}

Also your init() function should return a value or set to void.

Undefined reference to declared C++ static member variable

In C++, static variables are essentially syntactic sugar around global variables. Just like global variables, they must be defined in exactly one source file, with:

int Test::nb;

and if you want to initialize it with a particular value,

int Test::nb = 5; // or some other expression

C++ Class Method contains Undefined Reference to a Static Variable

You should not use the static keyword when defining the field in the .cpp file, only when declaring it in the class. Note in the code comments you have "declaring" and "defining" the wrong way round.

Additionally, when defining the member, you need to qualify it with the class name.

So the .cpp definition should be:

MyTest::DBGL MyTest::debug_level_d = MyTest::FULL;

By using the static keyword in the definition, you restrict it to internal linkage.

See: http://en.cppreference.com/w/cpp/language/static

Undefined reference to initialized static member variable with make_shared

Since C++17 the first code should work correctly: a static constexpr class member variable is implicitly inline which means the compiler takes care of making sure a definition exists .

Prior to C++17 the code has undefined behaviour (no diagnostic required) due to ODR violation. A static class member that is odr-used must also have an out-of-line definition.

Binding a reference to a variable counts as odr-use, and that happens with make_shared<int>(c) since that function is defined as :

template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );

so the argument is bound to a reference parameter.


In theory you should be able to work around it with make_shared<int>(+c) ... then the reference is bound to the temporary result of +c and not to c itself, therefore there is no odr-use. Similar theory to your posted workaround in the question.

enum { c = 0 }; is another possible workaround, if the type is int in the real code .



Related Topics



Leave a reply



Submit