Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ namespaces: cross-usage

Consider the following example. It consists of two header files, declaring two different namespaces:

// a1.h
#pragma once
#include "a2.h"

namespace a1 
{
    const int x = 10;
    typedef a2::C B;
}

and the second one is

// a2.h    
#pragma once
#include "a1.h"

namespace a2 {
  class C {
  public:
    int say() {
      return a1::x; 
    }
  };
}

And a single source file, main.cpp:

#include <iostream>
#include "a1.h"
#include "a2.h"

int main()
{
  a2::C c;
  std::cout << c.say() << std::endl;
}

This way it doesn't compile (tried GCC and MSVC). The error is that a1 namespaces is not declared (C2653 on Windows). If you change include order in main.cpp this way:

#include "a2.h"
#include "a1.h"

you get a symmetric error message, i.e. a2 namespace is not declared.

What's the problem?

like image 961
Andrew T Avatar asked Jul 21 '26 05:07

Andrew T


1 Answers

You need to use a forward declaration in your header files because you have a circular reference. Something like this:

// a1.h
#pragma once

namespace a2 {
    class C;
}

namespace a1 
{
    const int x = 10;
    typedef a2::C B;
}
like image 105
Greg Rogers Avatar answered Jul 23 '26 22:07

Greg Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!