Home > Software > C++ namespace’s and externally global variables

C++ namespace’s and externally global variables

November 20th, 2008

I ran across an interesting segmentation fault caused by trying to access a NULL pointer, that I thought should not be. Here’s what I had in my main source file:


Siphon::Logger *glogger = NULL;

...

int main( int argc, char **argv )
{
 ...
 glogger = new Siphon::Logger(); // initialize the global

}

Now in another source file;


namespace Siphon {

extern Siphon::Logger *glogger = NULL;
...

}

Later I realized this caused a warning, but initially, I just ran my code only to receive a segmentation fault when using the glogger in the second source file. Because, of the extern the compiler allowed this to slip by thinking it was Siphon::Siphon::Logger, instead of Siphon::Logger. To correct this, I could either move the line out of the namespace or remove the Siphon:: prefix.


extern Siphon::Logger *glogger;

namespace Siphon {

...

}

Software

  1. No comments yet.
  1. No trackbacks yet.
CommentLuv Enabled

Comments links could be nofollow free.