c++ static library is too big, why?
This is what I'm doing (this is an example, not a real-life syntax):
$ svn co http://svn.boost.org/svn/boost/trunk/libs/regex/src regex
$ c++ -o regex/*.obj -c regex/*.cpp
I have 17 *.obj
files in regex
. Now I'm trying to create a static library from them:
$ ar -r regex.lib regex/*.obj
The size of the library is 10Mb. Is it a correct size? Should it be that big with just 17 C++ files? I have a filling that thi开发者_JS百科s library contains duplicated symbols. Many of them.. Thanks in advance for some hint.
Yep, static libraries tend to be pretty big.
The reason is that they have to contain everything from the source files. The final executable can strip out all the symbols it doesn't need, but in a static library, you don't yet know which symbols are going to be needed, so everything has to be packed in there, often along with a lot of debugging info.
The size doesn't strike me as anything out of the ordinary. Of course, when you link it into an executable, the executable won't grow by that much.
What is the sum of the sizes of the constituent object files? That would pretty much be the expected size of the aggregated archive. The metadata added by ar should be minimal.
Use the nm utility to inspect the archive to see what object files and symbols it contains. The nm --size-sort switch maybe useful in quickly finding out what is occupying the largest amount of space in the archive.
You can't predict the size of the output from the number of source files. A file could contain a dozen lines of simple code, or thousands of lines of spaghetti, or a vast data table. Object files (and static libraries, which are just collections of object files) contain metadata used for linking, which can be removed from the final executable. They may also contain a large amount of debugging information, if the compiler was configured to generate that. You're building with no optimisation, which will usually bloat the code quite a bit. Inline functions will appear in every object file that uses them; linking will resolve these duplicates, but simply lumping the objects together with ar
won't.
I just did the same experiment: I got 3.5Mb rather than 10Mb to start with; adding debug information (-g
) increased it to 8Mb; enabling optimisation (-O3
) reduced it to 1.6Mb, about the same size as the version installed on my computer. The dynamic library installed on my computer (generated with a linker, not ar
), is smaller still, about 666kb.
But why are you worrying about the size of the library? Are you planning to distribute a product as a precompiled static library? On floppy disks? Are you trying to develop on an Amiga 500? If you're developing for a limited platform, then worry about the size and runtime footprint of the final executables.
精彩评论