c++ 'global' objects
-
keane
c++ 'global' objects
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
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.
Now you need to implement malloc and free.
Code: Select all
void *operator new(size_t bytes)
{
return malloc(bytes);
}
void operator delete(void *ptr)
{
free(ptr);
}Re:c++ 'global' objects
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:
Then call each constructor in turn in your startup code:
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.)
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)
}
...
}
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
Every good solution is obvious once you've found it.
