imulsion
imulsion

Reputation: 9040

Why are more common #include directives not included as default?

I'm thinking particularly of <iostream> here. Since it is such a common library that most C++ programs use, why is is not included as default? Other examples are <string>, <fstream> and <cstdlib>.

Upvotes: 1

Views: 239

Answers (4)

user657267
user657267

Reputation: 21010

It's ironic you picked <iostream> as an example:

The C++ Standard Library second edition, p.752

The header <iostream> should be included only if the standard stream objects are to be used. For some implementations, some code is executed at start-up for each translation unit including this header. The code being executed is not that expensive, but it requires loading the corresponding pages of the executable, which might be expensive.

Upvotes: 2

Mppl
Mppl

Reputation: 961

This things are not included because of performance/executable file size . By providing you the bare minimum things you might need your executable will have the minimum size possible and you will not be linking against libraries you don't use at all.

Including libraries you don't use may in some cases increase the loading time of you program.(This largely depends on you system loading strategy!). In terms of the performance of the program once loaded there shouldn't be a great difference (if there's any at all!).

Upvotes: 1

Arne Mertz
Arne Mertz

Reputation: 24626

That is because there is no common header that is used "a lot of the time".

E.g. <iostream> is used only in applications that do a lot of I/O via streams/console, and only if those applications do not use other libraries for the task (ncurses comes to mind for console). And in those applications it's only used in the module(s) that actually do the I/O, not in other modules that e.g. do the logic, calculations, persistence to databases etc.

The same pattern of reasoning applies for any other "often used" header. However, you might want to look up precompiled headers, if in your project there are headers that are used in a lot of places. But you might as well want to make your application modular and not use API headers in every place.

Upvotes: 3

ForEveR
ForEveR

Reputation: 55897

Common C++ idiom:

You pay only for what you use.

Upvotes: 6

Related Questions