I poorly understand the linkage process, and I'm struggling with multi-file compilation with template classes. I wanted to keep definitions in one file, declarations in another. But after a day of suffering, I found out that I should keep definitions and declarations in the same transition unit (see here). But my code still doesn't compile, and if I do not figure it out, I'll post another question.
But that's not the question. The question is: once I was reading about "keeping definitions and declarations in the same header" and it was considered as bad practice. One of the comments says:
The include guards protect against including the same header file multiple times in the same source file. It doesn't protect against inclusion over multiple source files
Makes sense, until I wanted to try this out with standard libraries in g++. I tried to do it with <vector>
, so I have two files:
main.cpp:
#include "class.h"
#include <vector>
template class std::vector<int>;
int main()
{
std::vector<int> arr;
}
class.h:
#include <vector>
std::vector<int> a(4);
I compiled with g++ main.cpp class.h
and it compiled successfully. But why? Didn't I included <vector>
twice, and therefore I have double definitions?
I checked header files on my machine, and they have definitions and declarations in the same file.