OneGuyInDc
OneGuyInDc

Reputation: 1565

why does declaring a static member in c++ cause the linker to link the atexit

If I declare sensor as static - the linker complains about an undefined reference to atexit.

If I declare the sensor as non static - it does not - WHY?

//Static function in a c++ class

AP_Compass_Backend *AP_Compass_HMC5843::detect(Compass &compass)
{

    static AP_Compass_HMC5843 sensor(compass);
    bool result = sensor.init();

    if (result == false) {
        return NULL;
    }
    return &sensor;
}

Upvotes: 1

Views: 276

Answers (2)

marcinj
marcinj

Reputation: 49976

If I declare sensor as static - the linker complains about an undefined reference to atexit.

it looks like compiler for your platform uses atexit function for destruction of static objects. Normally atexit is used by programmer if he/she want to execute some code after application ends.

If I declare the sensor as non static - it does not - WHY?

well, because then there are no static global objects whose destructors should be called.

It might be possible that you use some library/code which is not taking into account limitations of your platform, if it does not allow for destruction of static objects - then maybe thats because it is not possible scenario. I suggest adding empty atexit function as below:

int atexit(void (*func)()) {
    return 0;
}

Upvotes: 1

6502
6502

Reputation: 114461

Apparently in that platform the destruction of local static duration objects is done by registering an atexit call.

Destroying globals doesn't require anything because the destruction can be done explicitly when exiting main just calling all destructors in the proper order.

For local statics however the object may have been not constructed (if the function wasn't entered) so you need a way to register for destruction dynamically. Please rememeber that a function-level static object is constructed the first time the scope is entered (and ONLY if the scope is entered)... this is a guarantee of C++.

The dynamic destructor chain could have implemented manually (e.g. keeping a linked list), but relying on atexit seems another viable option.

Upvotes: 2

Related Questions