sandytaft
sandytaft

Reputation: 1

c++ namespace with class

ns.cpp:

    #include <iostream>

    namespace ns {        // want to access this globally
      class A ;
    }

    class ns::A {
    public:
     int x1;
     char s1[128];
    };

    int main()
    {
    int doit();
    //using namespace ns;

      ns::A a;

      a.x1= 2;

      std::cout << "pre " << a.x1 << "\n" ;
      doit();
      std::cout << "post " << a.x1 << "\n" ;
    }

ns_call.cpp:

    namespace ns {
     class A;
    }

    class ns::A {
    public:
     int x1;
     char s1[];
    };

    using namespace ns;

    int
    doit()
    {
       extern ns::A a;

       a.x1= 100;
    }

in ns.cpp, a class is declard within a namespace. the class is defined followed.

Variables in the class are to be accessed globally. This is the goal of the namespace.

ns_call.cpp then access 1 of the class' member, x1.

The 2 files were compiled OK with gcc 5.4.1 in Fedora 14. run output is:

pre 2
post 2

I expected 'post 100' because i wanted to access int x1 in class A globally.

Upvotes: 0

Views: 342

Answers (2)

yzt
yzt

Reputation: 9103

I'm just gonna help you fix your problem, while you absolutely have to heed the other answers about ODR (One Definition Rule) and fix your design.

in the ns.cpp file, you have to move the line ns::A a; out of the main() function. Put it at the file scope (e.g. right before main.) Also, in the ns_call.cpp file, move the line extern ns::A a; out of the function too.

Note: you may or may not have to do the second part, and this whole method might or might not work. I don't have access to a compiler right now.

Again I have to agree with other comments that this design is flawed and it will cause you headaches.

Upvotes: 1

John Dibling
John Dibling

Reputation: 101446

None of extern, namespaces or forward declarations seem to mean what you think they mean.

If you want to introduce a name that can be accessed my multiple translation units (what you seem to mean when you say "globally"), you put those definitions in a header file, and #include that header from wherever you want to use it.

What you're actually doing is introducing class A over and over again in every translation unit (eg, in each CPP file). This is a violation of the ODR at best.

Upvotes: 3

Related Questions