I'm using version 5.4.0 and simplest program (empty screen) have almost one megabyte. For example, after compilation this below simple program has 1 276 KB. But deleting #include makes file really small : 27 KB.
#include<iostream>
using namespace std;
int sum(int a){
if(a>1)
return sum(a-1)+a;
else
return 1;
}
int main(){
int a=1;
while(a>=0){
cout<<"a = ";
cin>>a;
cout<<"1+...+a = "<<sum(a)<<endl;
}
return(0);
}
It seems to me that it should be possible to generate a much smaller executable for the above. How do I go about achieving this?
Here are some ideas from my experience:
Review all source code and remove unused code, both unused functions and statement blocks that will not be executed. Use a static code analyzer to assist in finding them.
Don't use printf
unless necessary.
It hauls in a lot of code, especially for formatting floating point numbers.
Does your compiler haul in unused functions from library files?
Some compilers link in the whole library file rather than only the functions used from it.
Are you measuring debug (with symbols) or release (no symbols)?
Are you measuring the static library version or only code without dynamic libraries?
Review any inline functions.
Convert larger inline functions to not inline.
Remove common code out of templates and into functions.
Reduce the number of statically and globally initialized variables.
The initialization takes up space in your executable.
Declare constant variables as static const
wherever possible.
Place common text literals into one file and return references or constant pointers to them.
This will assist the compiler in merging duplicate strings across modules.
Analyze functions for common code fragments. Factor them into separate functions or methods.
Move some functionality into dynamic libraries. Let the OS determine when to use the code.
Remove all code related to future functionality that is not currently executed.
Data takes up room in your executable, especially values used for initializing static or global variables. Consider moving the data to a file and loading the data on demand.
Some of these suggestions will shrink your executable but not the application, such as data files and dynamic libraries. They will be required for your program to execute but may not be needed in the executable.
Some suggestions will slow the performance of your application. Sorry, it's the time/memory tradeoff: you can save memory but it will take more execution time (such as packing fields).