Page 1 of 1

Wiki: C PlusPlus - Static Objects

Posted: Tue Jan 13, 2009 11:21 am
by ChristianF
Hi,
may be it is a simple question, but it was coming up, when I read the in the title mentioned article.

The text says that to enable global objects, I need "int __cxa_atexit(void (* f)(void *), void *p, void *d);", which is right, because without the code it won't compile. There is the following Code in the Article, to implement this:

Code: Select all

extern "C"
        {
        int __cxa_atexit(void (*f)(void *), void *p, void *d);
        void __cxa_finalize(void *d);
        };

void *__dso_handle; /*only the address of this symbol is taken by gcc*/

struct object
{
        void (*f)(void*);
        void *p;
        void *d;
} object[32] = {0};
unsigned int iObject = 0;

int __cxa_atexit(void (*f)(void *), void *p, void *d)
{
        if (iObject >= 32) return -1;
        object[iObject].f = f;
        object[iObject].p = p;
        object[iObject].d = d;
        ++iObject;
        return 0;
}

/* This currently destroys all objects */
void __cxa_finalize(void *d)
{
        unsigned int i = iObject;
        for (; i > 0; --i)
        {
                --iObject;
                object[iObject].f(object[iObject].p);
        }
}
The Code works fine and I understood how it works, but why is object an Array with 32 elements?
Is it, that it looks a bit prettier or why?

Cheers Christian

Re: Wiki: C PlusPlus - Static Objects

Posted: Tue Jan 13, 2009 1:25 pm
by LMN
As there is no memory management at the start of a kernel memory regions have to be reserved beforehand. The 32 is just a freely defined value to reserve slots for 32 destructors at compile time. These will be filled at start of your kernel by compiler-generated calls to cxa_atexit (i think). So if you have more static objects, you should choose higher value.

Re: Wiki: C PlusPlus - Static Objects

Posted: Fri Jan 16, 2009 4:41 pm
by Owen
Hang on a minute - does a kernel ever exit like a normal user program? Is there really any need to store the destructor calling information anyway?

Re: Wiki: C PlusPlus - Static Objects

Posted: Sat Jan 17, 2009 4:25 am
by AJ
I don't bother storing this information for my kernel for that very reason - I think it's pointless generally. I can see two arguments against this:

* You want to exactly conform to standards :?
* Your destructor code actually does shutdown stuff (cache flushing, stopping usb drives, spinning down disks and so on..).

Cheers,
Adam