Page 1 of 1

Constructors are not called

Posted: Thu Oct 24, 2002 11:00 pm
by GSD
Hi,

after i stopped writing a new operating system in C, i started rewriting it in C++ (because there are only a few systems written in C++, it's just like a challenge). I'm writing it with GCC and NASM. But there's a little problem. Not a real problem, because there are a lot of work arounds, but it's a little bit confusing.

The constructors of the classes are not called, when creating new instances. Why ?

The resulting binary format after compiling is real binary, not ELF.

Is it possible, that a compiler switch causes this problem ?

Has anyone a real good idea to fix this ?


Rene

RE:Constructors are not called

Posted: Thu Oct 24, 2002 11:00 pm
by anton
All constructors of global vars are called in a function before main. As far as i remember it is init(disasm a binary to find out).
Anton

RE:Constructors are not called

Posted: Tue Oct 29, 2002 12:00 am
by The Legend
I would suggest you search for the "Singleton" design pattern in google. It might just be what you need and it is basically simple (unless you need it to be 100% thread safe ...)

RE:Constructors are not called

Posted: Mon Nov 11, 2002 12:00 am
by Anonymous
if these are global or static local objects:

1. the C++ compiler creates a little function to construct/destruct each object
2. it puts a pointer to each static constructor in the ".ctor" or ".ctors" section of the object (.o) file
3. same as #2 for destructors, but uses ".dtor" or ".dtors"
4. you must change your linker script -- you already have a linker script, RIGHT? -- to combine these sections into the kernel data segment and define the start/end, maybe like
...
    .data :
    {
/* static constructors */
start_ctors = .;
*(.ctor*)
end_ctors = .;
/* static destructors */
start_dtors = .;
*(.dtor*)
end_dtors = .;
/* kernel data */
g_data = .; _g_data = .;
*(.data)
. = ALIGN(4096);
    }
...
5. kernel startup code must call the static constructors before main():
...
/* sorry, 'as' syntax, not NASM... */
mov $start_ctors,%ebx
jmp 2f
.1:
call *(%ebx)
add $4,%ebx
.2:
cmp $end_ctors,%ebx
jb 1b
...

6. use code same as #5 to call the destructors when (if?) the kernel returns or exits