I have a namespace in which I’d like to define a class. The class is rather complex so I’d rather define it in a separate header file, but even the simplest code gives me an “undefined reference” error.
main.cpp
#include <iostream>
namespace A {
#include "C.hpp"
}
int main()
{
A::C foo;
std::cout << foo.member << std::endl;
return 0;
}
C.hpp
class C {
public:
C();
int member;
}
C.cpp
C::C()
{
this->member = 10;
}
When I run g++ C.cpp main.cpp I get “main.cpp:(.text+0x10): undefined reference to `A::C::C()'” error. I suppose that it’s the C::C() definition of the constructor that is somehow wrong, but I’m uncertain how to fix it.
This is a very odd thing to do.
This places everything declared in the header inside a namespace called
A; specifically, it gives you a declaration ofA::C, which is a different class to the::Cyou get when you include the header without a surrounding namespace.You have provided a definition for
::C::C(); butmain.cpprequires a definition forA::C::C(), since that is the class it uses. That’s not defined anywhere, hence the error.Either put
Cproperly intonamespace Aby moving the namespace to the header file (and fixC.cppto use that namespace), or get rid ofnamespace A.