Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for the entire C++ STL code to be included in the .h rather than .cpp/.c files?

I just downloaded the STL source code and I noticed all the definition for the STL template classes are included in the .h file. The actual source code for the function definition is in the .h file rather than .cpp/.c file. What is the reason for this?

http://www.sgi.com/tech/stl/download.html

like image 450
Judeo Avatar asked Dec 04 '22 14:12

Judeo


2 Answers

Because very few compilers implement linking of templates. It's hard.

Here's a brief but (I think) informative article about it: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=53

I say "I think" because it's really not something I'm very familiar with other than that it's widely unimplemented. I initially said the standard didn't require it, but looking at the definition of "export" in C++03, I don't see any indication that it's optional. Maybe it's just a failed standard.

like image 131
Steve Jessop Avatar answered Jan 01 '23 20:01

Steve Jessop


Think of templates as code generation. If you don't know beforehand what template will be used with, you can't compile. So you need to keep the implementation in the header.

This allows some inlining and that explains why sometimes using templated stuff (like std::sort) works faster than in plain C.

like image 24
Tristram Gräbener Avatar answered Jan 01 '23 19:01

Tristram Gräbener