[Fwd: Re: Undefined reference to static member]

bjorn rohde jensen bjensen@fastmail.fm
Tue Feb 4 20:40:00 GMT 2003


Hi Leo,

  You are only declaring the static member.
The nm -C dump of the object file

          U String::count

tells you, that it is Unresolved aka missing
from the object file.

In C++ a static member in a class declaration
is also just a declaration. Yout need to define
it as well.

Yours sincerely,

Bjorn

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

class String {
   char * tstr;
   static int count;

public:
   String( void ) {
     count ++;
     tstr = new char;
     *tstr = 0;
   }

   String( char * s ) {
     count++;
     tstr = new char[ strlen( s ) + 1 ];
     strcpy( tstr, s );
   }

   friend void report( void );
};

int String::count=0;     //definition of count:)

void report( void ) {
   printf( "Report on String Usage:" );
   printf ( " %d Strings created\n", String::count );
}

int main( int argc, char ** argv ) {
   String * test = new String();
   test = new String( "ha" );
   report();
   return 0;
}



More information about the Gcc-help mailing list