0

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 ?

Community
  • 1
  • 1
Guillaume Paris
  • 10,303
  • 14
  • 70
  • 145
  • 2
    Because compiler is not linker. Compiler handles only one compilation unit, by definition. To make .cpp file accessible, include it to current .cpp file (which actually means that it is used as .h file). – Alex F Dec 30 '13 at 11:47

3 Answers3

2

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

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 #included 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 #includes 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.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324