extern problems (c++)

Started by
4 comments, last by Eriond 20 years, 1 month ago
I'm trying to have a global object(not really global, should be in a namespace) of class X which is in namespace N.
// X.h

namespace N
{
    class X
    {
    public:
        void f();
    };

    class Y;
}

// X.cpp

#include "X.h"

namespace N
{
    X *x = 0;
    
    void X::f() { /*...*/ }

    //methods in Y that needs x.

}

// main.cpp

#include "X.h"
extern N::X *x;
x = new N::X;
x->f();
This gives me one linking error: error LNK2001: unresolved external symbol "class N::X *x" How do I fix that? [edited by - Eriond on March 21, 2004 1:21:40 PM] [edited by - Eriond on March 21, 2004 1:25:19 PM]
Advertisement
The object doesn''t exist. extern tells the compiler to look for its definition elsewhere; have you defined it anywhere?

Typically, this is solved by placing the extern declaration in a header file that will be included in multiple places and placing the instance definition in the implementation file where the object can be said to "live".
You''re putting not only the class definition, but also the global variable, in the namespace N. Therefore, when declaring it extern, you''ll have to declare it as N::X* N::x.

"Sneftel is correct, if rather vulgar." --Flarelocke
If I use extern N::X *N::x; in main.cpp I get "x is not a member of N".
Have you tried adding "extern X * x;" inside the namespace block, in X.h ? This might work, you would only need to include X.h to be able to use the global.

Victor Nicollet, INT13 game programmer

Now it worked, thanks for your help

This topic is closed to new replies.

Advertisement