I'm writing some code that's going to be used on an embedded device so I want to keep the code size down by having the linker discard some of the third-party library functions I'm not using. I've tried using the -ffunction-sections
and -fdata-sections
options along with -Wl,--gc-sections
but unused functions remain.
Here's an example I've built with MinGW:
#include <iostream>
using namespace std;
double unused_function(int a, int b)
{
double r;
r = (double)a + (1.0/ (double)b);
return r;
}
double used_function(int a, int b)
{
double r;
r = (double)a + (1.0/ (double)b);
cout << r << "is the value" << endl;
return r;
}
int main() {
cout << "!!!Hello World!!!" << endl;
used_function(4,5);
return 0;
}
Here's the command line output:
g++ -O1 -ffunction-sections -fdata-sections -g -Wall -c -fmessage-length=0 -o "src\\test.o" "..\\src\\test.cpp"
g++ -Wl,--gc-sections,-Map=output.map,--print-gc-sections -o test.exe "src\\test.o"
size --format=berkeley test.exe
text data bss dec hex filename
36424 2476 2608 41508 a224 test.exe
Now if I comment out unused_function()
entirely and rebuild, the size
command reports this:
text data bss dec hex filename
36388 2476 2608 41472 a200 test.exe
I would have expected that the unused function would have been discarded and thus the text size would remain the same but that's obviously not the case. Is there a command line option I'm missing or is this part of my own ignorance about how GCC works internally?
This is just an example to demonstrate my problem. I'm using some third party libraries for various functions and my goal is to ensure that parts of the libraries I don't use are removed from the code.