简体   繁体   中英

Why do I get double binary size when I instantiate a static object inside a free function in C++?

On an embedded system (Cortex-M4) I write C++ that compiles with GCC arm-none-eabi-g++ . Compiler version 10.2.1 20201103 .

My code is kind of complicated to copy paste it here, so here's an example:
I have a class that abstracts a hardware peripheral.

class A
{
public:
    void init(void)
    {
        // initializes hardware peripheral
    }
    // other public functions here
private:
   int x,y;
   // other private variables here
};

I want to use this class to use it inside an RTOS task.
in a.cpp file I have a free function myDriver_init that is linked with extern "C" keyword.
The free function myDriver_init creates an RTOS task and gives it a callback to run.

extern "C" myDriver_init(void)
{
    static A a;
    create_RTOS_task(&myDriver_state_machine, &a, priority, stack_size);
}

void myDriver_state_machine(void * param)
{
    A * a_ptr = static_cast<A*>(param);
    a_ptr->init();
    while(true)
    {
        //user code here...
    }
}

In main.c I call the C linked function like this

int main(void)
{
    myDriver_init();
    ...
    RTOS_Task_run();
}

The question is why do I get almost double size of binary when the object a is inside the functon myDriver_init ?

If I move it outside and use it as a global variable the size of the binary goes significantly smaller.

static A a;
extern "C" myDriver_init(void)
{
    create_RTOS_task(&myDriver_state_machine, NULL, priority, stack_size);
}

void myDriver_state_machine(void * param)
{
    a.init();
    while(true)
    {
        //user code here...
    }
}

Why is this happening?

The optimization I use is -O2 in both cases.

I thought static variables/objects within functions are placed in the heap. What's the difference here?

I see some std::bad_exception in the map file of the big binary. Despite having -fno-rtti and -fno-exceptions flags.

It appears that somehow the compiler produces more code into the final binary when you create static objects inside functions like my example in the question.
That piece of code has something to do with exceptions which is not a desirable result in my case.

Changing the linker flags from

-specs=nosys.specs

to

-specs=nano.specs

solves the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM