I have a class Angle with the << operator overloaded and two cpp files where the header file is included. I have a #ifndef statement to prevent the file from being included multiple times. However, it seems that it is included multiple times, as I got an error that operator << was defined multiple times. I then added a #warning satement to see when the file is included. In the compiler output it can be seen that the #warning is processed twice. If I move the definition to the cpp file it obviously works, but I still find the behavior in this case strange.
In my opinion the compiler shouldn't process the header file twice. Is there a reason for this behavior?
main.cpp
#include <iostream>
#include <cmath>
#include <cstdlib>
#include "Angle.h"
using namespace std;
int main() {
Angle a = (Angle)(M_PI/4);
cout << a << endl;
return EXIT_SUCCESS;
}
Angle.h
#ifndef ANGLE_ANGLE_H
#define ANGLE_ANGLE_H
#include <iostream>
class Angle {
private:
double value;
public:
explicit Angle (double value) {this->value = value; }
double getValue() const {return this->value;}
// Operators
operator const double() const {
return this->value;
}
};
#warning INCLUDING_ANGLE_H
std::ostream& operator << (std::ostream& os, const Angle& obj){
os << obj.getValue();
return os;
}
#endif //ANGLE_ANGLE_H
Angle.cpp
#include "Angle.h"
I'm compiling with the following command:
g++ main.cpp Angle.cpp -o angle
With the following error:
In file included from main.cpp:5:0:
Angle.h:19:2: warning: #warning INCLUDING_ANGLE_H [-Wcpp]
#warning INCLUDING_ANGLE_H
^
In file included from Angle.cpp:1:0:
Angle.h:19:2: warning: #warning INCLUDING_ANGLE_H [-Wcpp]
#warning INCLUDING_ANGLE_H
^
/tmp/cci53Hrd.o: In function `operator<<(std::ostream&, Angle const&)':
Angle.cpp:(.text+0x0): multiple definition of `operator<<(std::ostream&, Angle const&)'
/tmp/ccBbwtlD.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status