Hi,
I'm curious about the process that a standard compiler would use to "find" the source file for a given header. Prompted by this thread (
http://www.cplusplus.com/forum/beginner/30207/), I was reading about function and class templates, and trying to compare the pros and cons between a plain old "function library" header/source, and using a function template instead.
With a function library setup, we would have a header and a source file, one for the prototypes and the other for the implementations. From any project we want to use those functions in, we need only #include the header file (correct?) and the linker will somehow link the appropriate source file for the function implementation (do I understand this correctly? I think so...).
My question is how the compiler/linker knows which source file contains the implementations of the header prototypes. It can't be based off the #include statement, because many of the sources in a project may include that. Is it the like filename? x.h always links with x.cpp, y.h always links with y.cpp? It seems a fragile thing to be linking on, so I wonder if there's more behind the scenes.
Reading on templates here in the tutorials, I noted this particular statement:
Because templates are compiled when required, this forces a restriction for multi-file projects: the implementation (definition) of a template class or function must be in the same file as its declaration. That means that we cannot separate the interface in a separate header file, and that we must include both interface and implementation in any file that uses the templates. |
Why not, for a library of functions, just include both the function prototype and implementation in the header file, and do away with the source?
Thanks for any insight,
Jack