I am experiencing a problem with a C++ project for an STM32 ARM micro. I created a class that implement a state machine. This class has some methods that are not called directly by other methods, but just by function pointers:
// Foo.h
class Foo
{
public:
typedef void(Foo::*State)(void);
State state;
void init();
virtual void poll();
void state1();
void state2();
Foo();
virtual ~Foo() {}
};
// Foo.cpp
#include "Foo.h"
#define ASSIGN_STATE(X,Y) \
X = &Foo::state ## Y;
void Foo::init()
{
ASSIGN_STATE(state, 1);
}
void Foo::state1()
{
ASSIGN_STATE(state, 2);
}
void Foo::state2()
{
;
}
void Foo::poll()
{
(this->*state)();
}
Foo::Foo()
{
this->init();
}
I instanciate an object of this class with global scope:
Foo foo;
int main()
{
foo.init();
while(1)
foo.poll();
return(1);
}
If I compile the project the methods that are not directly called by other methods (state1()
and state2()
) are not linked and the firmware crashes when it calls them.
If instead I instantiate them inside main()
, the methods are linked and everything works correctly.
int main()
{
Foo foo;
foo.init();
while(1)
foo.poll();
return(1);
}
Compiler and linker flags:
COMPILER_FLAGS = $(DEBUG_FLAGS) -mcpu=cortex-m3 -mthumb -Wall -mlittle-endian -MD -MP -MF $(DEPS)/$(@F:%.o=%.d) -fno-strict-aliasing -fsigned-char -ffunction-sections -fdata-sections $(DEFINES) $(INCLUDES)
CPPCOMPILER_FLAGS = $(DEBUG_FLAGS) -mcpu=cortex-m3 -mthumb -Wall -mlittle-endian -MD -MP -MF $(DEPS)/$(@F:%.o=%.d) -fno-strict-aliasing -fsigned-char -ffunction-sections -fdata-sections -fno-rtti -fno-exceptions $(DEFINES) $(INCLUDES)
LINKER_FLAGS = -mcpu=cortex-m3 -mthumb -specs=nano.specs -lnosys -L$(LINKERSCRIPT_DIR) -T$(LINK_SCRIPT) -Wl,--gc-sections $(DEFINES)
The project is C/C++ mixed. I user the GCC ARM TOOLS toolchain to compile it, under the Windows 7 OS.
I tried with different compiler flags and different optimization options, but nothing changed. Any idea on why I get this behavior, or how I could investigate its causes?