Undefined refrence to static variable Foo::a?
I am getting this error and I have no idea what it means:
$ mingw32-g++ Test.cpp -o Test.exe开发者_如何学C
C:\Documents and Settings\BDL\ccksiYhI.o:Test.cpp:(.text+0x11): undefined reference to 'Foo::a'
collect2: ld returned 1 exit status
This is my code.
Test.cpp
#include <vector>
#include "Test.h"
int main() {
Foo::a.clear();
return 0;
}
Test.h
#include <vector>
class Foo {
public:
static std::vector<int> a;
};
This isn't my original code but I have boiled it down to this problem. I am new to c++ and if anyone can explain why this is wrong and how I can work around it I would appreciate it.
You still need to define the member variable, even if it's static. Change your Test.cpp to this:
#include <vector>
#include "Test.h"
std::vector<int> Foo::a; // <-- definition
int
main() {
Foo::a.clear();
return 0;
}
You need to define static members as well in one translation unit, e.g. in Test.cpp
:
std::vector<int> Foo::a;
Static members must be defined outside the class. Inside you have a declaration.
There are many sites online with examples. Search for "define C++ static members."
Good luck with it and welcome to SO.
精彩评论