Reputation: 15054
I have two namespaces (F
and M
) where I used typedef to define something. I use the typedef in one namespace to declare a variable in the other namespace.
For example I have these files:
File M.hpp
#ifndef M_HPP
#define M_HPP
#include "F.hpp"
namespace M{
typedef std::vector<F::myD> VectorDouble;
class M{
private:
VectorDouble Diction;
};
}
#endif // M_HPP
File F.hpp
#ifndef F_HPP
#define F_HPP
#include "M.hpp"
namespace F{
typedef double myD;
class MyF{
private:
M::VectorDouble myVar;
};
}
#endif // F_HPP
It is immediately clear that these two header files create a circular dependance so forward declaration may be necessary, but how to do that with namespaces and typedefs?
File namespace.cpp
to drive the code:
#include <iostream>
#include <vector>
#include "M.hpp"
#include "F.hpp"
int main(){
std::cout << "Learning how to access stuff in a namespace." << std::endl;
F::MyF myFInstance;
M::M myMInstance;
return 0;
}
When I try to compile, I get an error that my M
is an undeclared identifier (see exact error message below). I don't understand why M
isn't seen as a namespace
.
$ clang++ -std=c++11 -stdlib=libc++ namespace.cpp -o namespace
In file included from namespace.cpp:5:
In file included from ./M.hpp:5:
./F.hpp:12:9: error: use of undeclared identifier 'M'
M::VectorDouble myVar;
^
1 error generated.
How can I access a typedef from another namespace? Is this a forward declaration issue?
Upvotes: 1
Views: 852
Reputation: 63704
Your issue is that you have created circular includes.
By your own coding, your file F.hpp
can't be compiled without first including M.hpp
.
And M.hpp
can't be compiled without first including F.hpp
.
Therefore, neither header can be compiled. See this SO post for solutions to circular dependencies.
Edit:
You can forward declare your typedef like this.
File F_fwd.hpp
#ifndef F_FWD_HPP
#define F_FWD_HPP
namespace F{
typedef double myD;
}
#endif // F_FWD_HPP
Upvotes: 1
Reputation: 98
your two headers are included in each other, that would lead to circular reference and with the header gaurds, one file can be completely excluded in one of the other headers.
Upvotes: 0