Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My C++ object file is too big

I am working on a C++ program and the compiled object code from a single 1200-line file (which initializes a rather complex state machine) comes out to nearly a megabyte. What could be making the file so large? Is there a way I can find what takes space inside the object file?

like image 706
zaratustra Avatar asked Jan 22 '09 19:01

zaratustra


3 Answers

There can be several reasons when object files are bigger than they have to be at minimum:

  • statically including dependent libraries
  • building with debug information
  • building with profiling information
  • creating (extremely) complex data structures using templates (maybe recursive boost-structures)
  • not turning on optimizing flags while compiling (saves not that much and can cause difficulties if used too extremely)

At first I suggest to check if you're building with debug information, this causes the most bloat in my experience.

like image 179
Kosi2801 Avatar answered Nov 16 '22 13:11

Kosi2801


(I'm assuming you've got optimisations and dead code stripping turned on).

Turn on your linker's "generate map file" option and examine the output.

Common culprits are macros/templates that produce large amounts of code, and large global objects.

like image 35
moonshadow Avatar answered Nov 16 '22 13:11

moonshadow


Possibly some template instantiations (especially the std::iostreams), and maybe extensive inlining (i.e. classes which are fully defined in a header). However, what's the problem with a 1-megabyte object file in the first place? During linking, it might very well result in a tiny binary. I got a project here with 20 MiB of object files which gets linked into a 700 KiB binary for example.

Update: Could be also some large static array/object. Besides that, with MSVC++ and GCC, you can look at the generated assembly for a file, which can give you some hints (with GCC, it's g++ -S foo.cpp, for MSVC++, it's '/FAs'). Either you will see a lot of template instances, then these are the reason. If not, it's the object size of static objects.

like image 41
Anteru Avatar answered Nov 16 '22 15:11

Anteru