I am working on a static library which gets linked into multiple binaries. My objective is to reduce the memory footprint of my library when it gets linked in.
The users of my library require certain global objects that I create in a cpp file in my library and then export a header file which has extern declarations of these variables.
Problem is, depending on how the library gets used, some of these global variables may not get used at all.
The following code shows the structure of my code somewhat:
Foo.hpp:
class Foo
{
static int sFooListIndex = 0;
static Foo * sFooList[10] = { nullptr };
public:
Foo()
{
if(sFooListIndex < 10)
{
sFooList[sFooListIndex++] = this;
}
}
}
Bar1.hpp:
#include "Foo.hpp"
class Bar1 : public Foo
{
public:
Bar1() : Foo() { }
}
Bar2.hpp:
#include "Foo.hpp"
class Bar2 : public Foo
{
public:
Bar2() : Foo() { }
}
Globals.cpp:
#include "Bar1.hpp”
#include "Bar2.hpp"
static Bar1 bar1;
Foo & foo1 = bar1;
static Bar2 bar2;
Foo & foo2 = bar2;
Export.hpp:
#include "Foo.hpp"
extern Foo & foo1;
extern Foo & foo2;
Here's my questions:
If the project that includes my library only uses foo1, then will foo2 get stripped out from the final binary? And thus will the code for the class Bar2 get stripped out as well?
If not, do you know how I can restructure my code such that the unused symbols and the unused code gets stripped out during linking? The only way I can think of is moving Globals.cpp and Export.hpp into the project that includes my library. Is there any other way?
One way I can think of is moving splitting Globals.hpp and Export.hpp into smaller files with groups of declarations and definitions that make sense together. Would that help?