So, I have a class A, the declarations for which are placed in the header file "a.h"
class A{
public:
static void init();
void print_hello();
};
extern A obj;
The member definitions are placed in "a.cpp"
#include "a.h"
#include "iostream"
void A::init(){
A obj;
}
void A::print_hello(){
std::cout << "hello\n";
}
Now, I have a third file "b.cpp" which has the main function
#include "a.h"
int main(){
A::init();
obj.print_hello();
return 0;
}
I basically want to have one instance of the class A that once initialized should be available to all the translation units in my program, hence why obj
has been made extern, now I want to be able to define obj
without having to make any other instance of class A
, this is the reason why I made the init
function static.
But once I compile the files
g++ a.cpp b.cpp -o test
The compiler throws an error
/usr/bin/ld: /tmp/ccjkarG1.o: warning: relocation against `obj' in read-only section `.text'
/usr/bin/ld: /tmp/ccjkarG1.o: in function `main':
b.cpp:(.text+0x10): undefined reference to `obj'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
I can't figure anything out other than the fact that it probably has to do something with the linkage process. I know extern keyword means external linkage. The keyword static here in the member function however does not mean internal linkage, but it simply means that this function can be treated as a simple function under the class namespace.
What's wrong here?