LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   "undefined reference"linker error for static field w/ C++ (https://www.linuxquestions.org/questions/programming-9/undefined-reference-linker-error-for-static-field-w-c-382329/)

astorm 11-12-2005 12:05 AM

"undefined reference"linker error for static field w/ C++
 
I get the linker error

/tmp/ccHfwmmN.o(.text+0x12): In function `Test::Foo()':
: undefined reference to `Test::signList'

with
Code:

class Test {
public:
  static vector<string> bar;
  static void Foo();
}

void Test::Foo()
{
  bar.push_back("donut snack");
}

int main()
{
  Test::Foo();
}

I tried initializing bar to NULL, but then the compiler says that bar is undeclared. Any help at all would be greatly appreciated.

Thanks in advance,
Alek

paulsm4 11-12-2005 12:51 AM

You only "declared" bar. Somewhere, you need to define (allocate space for) the actual variable "Test::bar".

coldAndUgly 11-12-2005 12:55 AM

Hi, both static member functions and data members must be defined somewhere.
Add this definition after the class.
Code:

vector<string> Test::bar;
Only constant integral static members may be initialised.
Code:

class Test {
public:
        static const int i = 0;
};


astorm 11-12-2005 09:06 PM

Thanks a lot for your help. It works now,

paulsm4 11-12-2005 09:14 PM

Cool! That particular subtlety bit me the first time I played with static members, too!

jpmueller 08-27-2008 03:00 AM

Thanks!
 
I had that problem too, it works perfect now. Thank you!


All times are GMT -5. The time now is 05:58 AM.