Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ produces big binaries despite small project

Probably this is a common question. In fact I think I asked it years ago... but I can't remember the answer.

The problem is: I have a project that is composed of 6 source files. All of them no more than 200 lines of code. It uses many STL containers, stdlib.h and iostream. Now the executable is around 800kb in size.... I guess I shouldn't statically link libraries. How to do this with GCC? And in Eclipse CDT?

EDIT: As I responses away from what I want I think it's the case for a clarification. What I want to know is why such a small program is so big in size and what is the relationship with static, shared libraries and their difference. If it's a too long story to tell feel free to give pointers to docs. Thank you

like image 231
gotch4 Avatar asked Oct 16 '25 13:10

gotch4


2 Answers

If you give g++ dynamic library names, and don't pass the -static flag, it should link dynamically.

To reduce size, you could of course strip the binary, and pass the -Os (optimize for size) optimization flag to g++.

like image 156
gnud Avatar answered Oct 19 '25 03:10

gnud


One thing to remember is that using the STL results in having that extra code in your executable even if you are dynamically linking with the C++ library. This is by virtue of the fact that the STL is a bunch of templates that aren't actually compiled until you write and compile your code. Since the library can't anticipate what you might store in a container, there's no way for the library to already contain the code for that particular usage of the container. Same goes with algorithms and everything else in the STL.

I'm not saying this is definitely the reason your executable is so much larger than you expect. But it may be a factor.

like image 45
Dan Moulding Avatar answered Oct 19 '25 04:10

Dan Moulding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!