Search code examples
c++staticatexit

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;
}

Solution

  • 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;
    }