c++ 'global' objects

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
keane

c++ 'global' objects

Post 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?
Tim

Re:c++ 'global' objects

Post 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.
User avatar
Solar
Member
Member
Posts: 7632
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:c++ 'global' objects

Post 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.)
Every good solution is obvious once you've found it.
Post Reply