Page 1 of 1

c++ 'global' objects

Posted: Sun Mar 21, 2004 6:22 am
by keane
I've read the faq and it says for global objects to use 'new()'. How do you put an object in memory and wheres the best place to put it?

Re:c++ 'global' objects

Posted: Sun Mar 21, 2004 7:45 am
by Tim
The compiler handles the first question. All you need to do is provide a memory block big enough to hold the memory the compiler asks for. You need implement operator new and operator delete.

Code: Select all

void *operator new(size_t bytes)
{
    return malloc(bytes);
}

void operator delete(void *ptr)
{
    free(ptr);
}
Now you need to implement malloc and free.

Re:c++ 'global' objects

Posted: Sun Mar 21, 2004 9:12 am
by Solar
Note that you can have global objects without implementing operator new() or anything. (Where in the FAQ does it say otherwise?)

Just declare a global object. At least with GCC / ELF, you will get one or more ".ctor*" section(s) in your object file, which basically hold arrays of pointers to the constructors of your global objects.

Link them into the kernel binary like this:

Code: Select all

ENTRY (kernel_loader)

SECTIONS
{
    ...

    .data ALIGN (0x1000) :
    {
        start_ctors = .;
        *(.ctor*)
        end_ctors = .;
        *(.data)
    }

    ...
}
Then call each constructor in turn in your startup code:

Code: Select all

               # calling global / static constructors
               mov  $start_ctors, %ebx
               jmp  2f
1:             call *(%ebx)
               add  $4, %ebx
2:             cmp  $end_ctors, %ebx
               jb   1b
There you have your global object. This is known to work. (I use a global object "kout" for printing to screen, constructed just like this.)