Wiki: C PlusPlus - Static Objects

All about the OSDev Wiki. Discussions about the organization and general structure of articles and how to use the wiki. Request changes here if you don't know how to use the wiki.
Post Reply
ChristianF
Member
Member
Posts: 79
Joined: Sun Jun 10, 2007 11:36 am

Wiki: C PlusPlus - Static Objects

Post 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
42
User avatar
LMN
Posts: 16
Joined: Tue Dec 30, 2008 6:11 pm
Location: Germany

Re: Wiki: C PlusPlus - Static Objects

Post 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.
User avatar
Owen
Member
Member
Posts: 1700
Joined: Fri Jun 13, 2008 3:21 pm
Location: Cambridge, United Kingdom
Contact:

Re: Wiki: C PlusPlus - Static Objects

Post 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?
User avatar
AJ
Member
Member
Posts: 2646
Joined: Sun Oct 22, 2006 7:01 am
Location: Devon, UK
Contact:

Re: Wiki: C PlusPlus - Static Objects

Post 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
Post Reply