After programming for a while in C, I decided to finally start to learn C++. This is sort of bothering me, as the standard 'hello world' in C is usually ~16KB, including all of the crud your compiler throws on there. (Using stdio)
However, when I create a C++ executable doing hello world, the file is ~470KB! I went ahead and used cstdio instead of iostream, thinking it would make a difference and it did.
My question is: When I include iostream, why does the size of my executable explode?
Edit: I'm using G++ (With the Dev-CPP IDE, but I can figure out how to add CL paramaters)
In a word, symbols.
The C++ standard library introduces a lot of symbols to your program, since most of the library exists primarily in the header files.
Recompile your program in release mode and without debug symbols, and you can easily expect the program to be significantly smaller. (Smaller still if you strip symbols.)
As a quick demonstration of this fact, observe:
$ cat hello.c
#include <stdio.h>
int main() {
printf("%s\n", "Hello, world!");
return 0;
}
$ cat hello.cpp
#include <iostream>
int main() {
std::cout << "Hello, world!\n";
return 0;
}
$ gcc hello.c -o hello-c
$ g++ hello.cpp -o hello-cpp
$ gcc hello.c -ggdb -o hello-c-debug
$ g++ hello.cpp -ggdb -o hello-cpp-debug
$ gcc hello.c -s -o hello-c-stripped
$ g++ hello.cpp -s -o hello-cpp-stripped
$ gcc hello.c -s -O3 -o hello-c-stripped-opt
$ g++ hello.cpp -s -O3 -o hello-cpp-stripped-opt
$ ls -gG hello*
-rwxr-xr-x 1 6483 Nov 14 15:39 hello-c*
-rw-r--r-- 1 79 Nov 14 15:38 hello.c
-rwxr-xr-x 1 7859 Nov 14 15:40 hello-c-debug*
-rwxr-xr-x 1 7690 Nov 14 15:39 hello-cpp*
-rw-r--r-- 1 79 Nov 14 15:38 hello.cpp
-rwxr-xr-x 1 19730 Nov 14 15:40 hello-cpp-debug*
-rwxr-xr-x 1 5000 Nov 14 15:45 hello-cpp-stripped*
-rwxr-xr-x 1 4960 Nov 14 15:41 hello-cpp-stripped-opt*
-rwxr-xr-x 1 4216 Nov 14 15:45 hello-c-stripped*
-rwxr-xr-x 1 4224 Nov 14 15:41 hello-c-stripped-opt*
I can't explain why a Windows build of the programs with G++ produces such large executables, but on any other platform, symbols are the primary driving factor in large file sizes. I don't have access to a Windows system at the moment, so I can't test.
Becuase you've dragged in most of the standard library by using iostreams. It's a one off thing though so as your programs gets larger it will seem less and less of an overhead.
However you probably want to compile using a shared library version of the standard library and most compilers / operating systems will let you do this so you'll not have to include all of the standard library in your executable. Which compiler are you using and we can likely advise on how to do that.
On windows with VC command line, use the /MD command line option for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With