The following link partially answer this question:
Why can templates only be implemented in the header file?
but the following remain :
Why the .cpp is not accessible by the compiler ?
The following link partially answer this question:
Why can templates only be implemented in the header file?
but the following remain :
Why the .cpp is not accessible by the compiler ?
The language is specified so that compilers can compile one "translation unit" (a source file, plus all the headers it includes) at a time, with no need to refer to any other source files at that stage. This is to allow a large program to be built without the compiler having to hold all of it in memory - that would have been impossible when this compilation model was developed (half a century or more ago), and would still be problematic today.
Therefore, definitions from one source file aren't available in others, and you can't do anything (such as instantiating a template) that requires such a definition.
Basically, because the compiler doesn't know which other .cpp to consult. The compiler gets to compile only a single .cpp file at a time.
That's just not how the compilation process works. It doesn't go looking for files itself. It just compiles the files you tell it to compile, pasting the contents of files that are #include
d into them. The general practice is that .cpp
files #include
header files and are then compiled as one single translation unit.
If you have foo.h
that contains a class template without function definitions (they're in foo.cpp
) and a main.cpp
that #include
s it, that translation unit will not have the function definitions. But it needs to have the function definitions to be able to instantiate the template. Putting both #include "foo.h"
and #include "foo.cpp"
in main.cpp
would fix it, but this goes against the commonly accepted practice of only ever including header files. It would also mean that every file would need to remember to include both. Some people like to have the function implementations in a foo.tpp
file which is then included at the bottom of foo.h
. This performs the same job.
But the main point is that the C++ compiler doesn't find go and locate files itself. It only compiles files that you tell it to.