Other Parts Discussed in Thread: MSP430G2210, MSP-FET, CCSTUDIO
[The present question is a cleaner version of this recent question. I wrote a minimal code that I can post in its entirety.]
I have noticed that instantiating objects as global variables bloats the code size. For small low cost microcontrollers, this is an issue. Here's a test case.
The setup: CCStudio 6.1.1.00022, MSP-FET via Spy-Bi-Wire, MSP430G2210.
Test code. The idea behind the test is to create several simple classes, instantiate them in different ways, observe the code size with Optimizer Assistant.
class Foo {
public:
unsigned int GetDummy();
void SetDummy(unsigned int iValue);
private:
unsigned int m_iDummy;
};
unsigned int Foo::GetDummy() {
return m_iDummy;
}
void Foo::SetDummy(unsigned int iValue) {
m_iDummy = iValue;
}
class Foo;
class Bar {
public:
Bar(Foo* pFoo);
void SetDummy(unsigned int iValue);
private:
Foo* m_pFoo;
};
Bar::Bar(Foo* pFoo) {
m_pFoo = pFoo;
}
void Bar::SetDummy(unsigned int iValue) {
m_pFoo->SetDummy(iValue);
}
These classes are instantiated in the three test cases.
Case 1. Local variables in main().
int main(void) {
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
Foo objFoo;
Bar objBar(&objFoo); //*/
objFoo.SetDummy(123);
objBar.SetDummy(234);
return 0;
}
Case 2. Global variables.
Foo g_objFoo;
Bar g_objBar(&g_objFoo); //*/
int main(void) {
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
g_objFoo.SetDummy(123);
g_objBar.SetDummy(234);
return 0;
}
Case 3. Global pointers. Objects newed-up in main().
Foo* g_pFoo;
Bar* g_pBar;
int main(void) {
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
g_pFoo = new Foo;
g_pBar = new Bar(g_pFoo);
g_pFoo->SetDummy(123);
g_pBar->SetDummy(234);
return 0;
}
Results
It's visible from the chart that globals consume more code space than locals. But these are the same objects in the same quantities in all cases. What's going on there?
