I tested the following code(just for test, I know it's a bad idea), and I couldn't understand why it has an error. Please help me!
There are two classes A and B, both in separate hpp files. I let them include each other(I think it doesn't matter because of the include guard), and it didn't go wrong until I added the definition of B::fun in B.cpp.
A.h
#ifndef A_H
#define A_H
#include "B.h"
class A {
friend void B::fun(A&);
};
#endif
B.h
#ifndef B_H
#define B_H
#include "A.h"
class A;
class B {
public:
void fun(A&);
};
#endif
B.cpp
#include "B.h"
void B::fun(A& a) {
}
main.cpp
#include "A.h"
#include "B.h"
int main() {
}
I run it with command like this:
g++ -g -o test main.cpp B.cpp
Error message
A.h:7:17: error: 'B' has not been declared
friend void B::fun(A&);
I know two workarounds for the symptoms, but I want to understand the problems root cause.
Method 1:
comment the code #include "A.h" in B.h
Method 2:
Modify #include "B.h" to #include "A.h" in B.cpp
I want to know why these workarounds avoid the symptoms, the exact reason for both methods.