Undefined reference to declared C++ static member variable [duplicate]
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
What does it mean to have an undefined reference to a static member?
To understand this, you should have a good understanding of compiling and linking, and the differences between declarations and definitions.
Consider the following class:
//In header file
class Example {
static bool exampleStaticMember;
};
Here, exampleStaticMember
is declared but not defined. This means that if exampleStaticMember
is used in a way that means that it must have an address then there must be a separate definition for it. In general, no declaration of a static data member in a class definition is a definition of that member.
The required declaration is usually put in the cpp file which contains the other definitions for the members of the class. It must be in the same namespace as the class definition. The definition typically looks like:
//In source file:
//This may optionally have an initialiser (eg "= true")
bool Example::exampleStaticMember;
The definition can be put in any cpp file, but it should not be put in the header with the class, because that would be likely to break the One Definition Rule.
As a special case, if the static member variable is an const integral or enumeration type then it can have an initialiser in the class definition:
//In header file
class Example {
static const int initialised = 15;
};
In this case, the definition in the cpp file is still required, but it is not allowed to have an initialiser:
//In source file
//Note: no initialiser!
const int Example::initialised;
Static members that have been initialised like this can be used in constant expressions.
Templates
For a static data member of a template, things are slightly different. The static member should be defined in the header along with the rest of the class:
//In header file
template<typename T>
class Example {
static int exampleInt;
static T exampleT;
}
template<typename T> int Example<T>::exampleInt;
template<typename T> T Example<T>::exampleT;
This works because there is a specific exception to the One Definition Rule for static data members of class templates.
Other uses of static
When the static
keyword is applied to functions and objects that are not in a class scope it can take on a very different meaning.
When applied to objects in a function scope, it declares an object that is initialised in the first execution of the function and that subsequently keeps its value between function calls.
When applied to objects or functions at namespace scope (outside of any class or function definition), it declares objects or functions with internal linkage. This usage is deprecated for objects, as the unnamed-namespace provides a better alternative.
undefined reference to static member variable in a static member function [duplicate]
Put this in a source file (by the looks of it MapObject.cpp
)
#include "MapObject.h"
float MapObject::xoffset = 0;
float MapObject::yoffset = 0;
//... the rest of your MapObject code here...
In C++ non-const static
members must be both declared in the class definition and defined with global scope to properly give the linker something to reference.
undefined reference to protected static member. How do I solve it?
You should be able to get rid of static bool hasBeenInitialised;
and bool robot::hasBeenInitialised=false;
as well as your initialization function and just declare uint_least8_t robot::NumOfRobots = 0;
and robot* robot::poiRobot = nullptr
directly in your cpp file. This way they initialize themselves to 0 and null automatically. As mentioned in the comments this is valid, protected static variables should be able to be defined in the source file in this manner.
Edit: In regards to the code you posted in your edit, it looks like you are never defining robot::poiRobot and robot::NumRobots. Did you try the code I posted above?
Basically, each cpp file in your project must be compiled into a translation unit by the compiler. Then the linker comes through and takes all of the translation unit's and links them together. Any cpp file that sees your robot class will see that you've promised that those 2 variables exist somewhere, and therefore when you use them it will allow it (as far is it is concerned, they exist and are good to go). When the linker comes along it will see references to those variables and try to find which translation unit they were defined in so that it can do its job (link everything together). At this point, it won't see a definition in any translation unit, and that is why it gives you that error.
uint_least8_t robot::NumOfRobots = 0;
and robot* robot::poiRobot = nullptr
are the definitions you are looking for, and should go in your cpp file. If after using those you get another error about them being protected as you had hinted at earlier, post that code so we can see why that is happening.
Edit 2 in regards to "It seems that I can't initialise my static variables in the class definition.": When you put that definition in the header file, each cpp file that includes your header will define it's own version of that variable. When the linker goes to link everything it will see multiple definitions in different translation units for the same variable and that violates the "One Definition Rule" in C++ (ODR). That is why it will give you an error. It is correct to put it in robots.cpp so only 1 translation unit (robots.cpp in this case) will have the definition. Then you have to make sure that robots.cpp is being compiled in your project so that the translation unit is available for the linker... as you could mistakenly just include robots.h in your source files, but never tell the compiler to compile robots.cpp.
Undefined reference to static member of class
In Rules.cpp
, you don't define the static members Rules::suits
and Rules::ranks
, but rather introduce 2 new global variables.
In order for the static definition to work, you need to specify the fully qualified name, e.g. Rules::suits
.
Undefined reference to static variable [duplicate]
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.
Using static results in an undefined reference in this piece of code [duplicate]
When you declare a static member in a class, C++ requires you to define the member outside of the class explicitly. Put this outside of your class in the .cpp file:
/*static*/
EventQueuePtr commonQueue::m_eventQueue;
undefined reference to a static function
#include "a.h"
void funcA(int i) {
std::cout << i << std::endl;
}
should be
#include "a.h"
void A::funcA(int i) {
std::cout << i << std::endl;
}
Since funcA
is a static function of your class A
. This rule applies both to static and non-static methods.
Related Topics
Calling C++ Member Functions Via a Function Pointer
Why Can't I Make a Vector of References
How to Execute a Functor or a Lambda in a Given Thread in Qt, Gcd-Style
Why Can In-Class Initializers Only Use = or {}
Is There a Standard Sign Function (Signum, Sgn) in C/C++
C++ Sorting and Keeping Track of Indexes
How to Use Std::Maps With User-Defined Types as Key
How to Print Function Pointers With Cout
Stack, Static, and Heap in C++
Why Should the Implementation and the Declaration of a Template Class Be in the Same Header File
Difference Between the Dot (.) Operator and -≫ in C++
What How to Do With a Moved-From Object
C++ Convert String (Or Char*) to Wstring (Or Wchar_T*)
Reading Every Nth Frame from Videocapture in Opencv
Fast Bignum Square Computation
How to Tokenize a String in C++
Reflection and Refraction Impossible Without Recursive Ray Tracing