I've Googled this, but most of the results are about compiler A vs. compiler B.
This question arises from my experience with Web Design (know the languages commonly used on Web Design aren't compiled. CGI is an exception.) When you include file in a web page the entire file is downloaded to the user's computer. If you use JQuery, a JavaScript library, you must include JQuery in the <head>
in order to use its functions. This got me thinking about C++ compilers.
In C++ it's practically impossible to program without #include <library>
. Are the libraries compiled along with the project files? Is the
For example, in this simple Hello Word program #include <iostream>
, is all of the code in the iostream header file compiled? Will taking ONLY the code that defines cout
and adding it to this example make the size of the file smaller? Does compiler optimization take care of only compiling the necessary code from iostream
?
#include <iostream>
int main()
{
std::cout<<"Hello World.";
return 0;
}
For example, in this simple Hello Word program #include , is all of the code in the iostream header file compiled? Will taking the ONLY the code that defines cout and adding it to this example make the size of the file smaller? Does compiler optimization take care of only compiling the necessary code from iostream?
Yes and no. C++ includes are a remarkably simple mechanism. The included header really is just concatenated with the including file, so yes, the simple answer is that you get everything you include.
But once everything has been included in this manner, the compiler does try to eliminate all the bits that aren't used. For many (not all) headers, this is easy to observe: if you compile a simple Hello World program, look at the file size, and then include a few more headers and recompile it, the executable size will typically be the same (or almost the same). The compiler determines that much of the cruft you included is never used, and removes it again.
There are exceptions, however. Some headers, just by being included, cause code to be run when the application is launched, for example, meaning that even if you don't refer to anything included from the header, the compiler can't remove it.