Reputation: 133
Here I have a very simple Point class:
namespace wtf{
template<typename T> class Point{
public:
T x;
T y;
Point(T xx, T yy): x(xx), y(yy) {};
};
}
As a templated class, it is my understanding that there cannot be separate header/implementation files as usual.
If I name the file that contains this class Point.cpp
, and compile it to a shared library as shown below, the file size is 5.6K, which seems reasonable. If I rename the file to Point.hpp
(Or .hxx
or .h++
), however, the file size grows to 1.9M! Clearly gcc
is processing these two file types differently!
Before I stripped this down to a MWE, there were additional standard lib includes (sstream
and iostream
), which brought the file size up to 11M! That also might give a little more of a clue about what is going on, though...
I am curious about what is actually happening here, and whether there are other ways that gcc
treats header files and code files differently. Mostly I have used gcc
5.2.0, though the same thing happened with older versions.
I do understand that it is probably not typical to try and compile a header file, but since I did try and found a funny result, I would like to know what's going on!
Thanks!
EDIT: Removed image.
Upvotes: 0
Views: 979
Reputation: 96791
You've tricked your compiler into naming the file libPoint.so
, while in fact it's not a shared library.
Which effectively means the compiler processes the entire header and saves it's own state to a file. Later, when you give it a .c
/.cpp
file which starts with #include "Point.hxx"
, it loads the state from the precompiled header, so it doesn't need to process it again. Thus, your code compiles faster. In a source file, only the first included header can benefit from this.
If you remove -o blah.so
from your command, GCC will name it Point.hxx.gch
, which is the intended name for a precompiled header. In fact, GCC won't even find your PCH if it's named differently.
Upvotes: 3