tags:

views:

505

answers:

5

I am getting the following error when trying to add a static variable to my struct:

Undefined Symbole s2::aa in module file_name.cpp

s2 is the name of the structure and aa is the static variable. The compiler I am using is Turbo C++ 3.0.

How do I fix this error?

+4  A: 

Static variable isn't allowed in structs in C because C requires the whole stucture elements to be placed together. To get an element value from a structure you count by the offset of the element from the beginning address of the structure.

However as far as I know you can have a static member in a C++ structure. Are you getting a specific error (which compiler?)

Otávio Décio
Yes I have got an error.A Linker Error"Undefined Symbole s2::aa in module file_name.cpp" (here 's2' is the name of the Structure and 'aa' is the static variable)Turbo C++ 3.0
Turbo C++ ?? Man, get a real compiler.
Otávio Décio
The error, as noted, is not a compilation error; it's a linking error, and happens because s2::aa is not defined anywhere. See Nick Meyer's answer for an example of how such a variable is defined.
Chris Jester-Young
thank you :) .......
+3  A: 

Why do you say this? Under g++ 4.1.2, this compiles:

#include <iostream>

struct Test
{
   static int test; // declare (usually in header file)
};

int Test::test = 8; // define (usually in source file)

int
main()
{
   std::cout << Test::test << std::endl;
   return 0;
}
Nick Meyer
+2  A: 

Static variables are allowed in C++ structs (as you say, they are just classes with a different default access specifier).

Static variables are not allowed in C structs, however.

William
+1  A: 

This works...

typedef struct _X
{
    static int x; // declare (usually in header file)
} X;

int X::x = 1; // define (usually in source file)

void _tmain(int argc, _TCHAR* argv[])
{
    printf("%d", X::x);
}
Ariel
+11  A: 

I think you've probably forgotten to define the storage for the static variable:

int C::v = 0;
Daniel Earwicker
Of course, the error message the OP posted says it all. :-)
Chris Jester-Young
Although, in this case, the "= 0" is optional; IIRC (on some platforms), static data that are at default values can be allocated in .bss, whereas initialized data would be in .data.
Chris Jester-Young
Static data is zero-initted on all platforms. Can be nasty if you change your mind and use the heap instead. Suddenly you discover that you forgot to init a member of the class.
Daniel Earwicker