开发者

Compiling C++ under Linux without the runtime library

I have recently started to explore the way that the C++ runtime library is used by the generated code.

Mostly I am very curious, but I also want to evaluate the amount of work needed to develop the minimum required stuff to start a kernel in C++.

So I started to implement my own runtime library, but I have a small issue.

int main(int argc, char **argv)
{
  return 0;
}

Compiling this with the following command:

$ g++ -ffreestanding -nostdlib -fno-builtin -fno-rtti -fno-exceptions -c main.cpp

I get this warning:

/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 00000000080480b8

Then when I try to execute the binary produced I get a "Segmentation fault". I have tried to compile "main.cpp" and an ASM file.

[global _start]
[extern main]

_start:
  call main

Linking the object files manually with "ld", I don't have the warning but the binary is still raising a "Segmentation fault".

I supp开发者_Python百科ose I am missing something. Probably something that has to be done before and after the call to "main" as the system C library does in "__libc_start_main" for instance.

Also, if someone has any recommendation of websites, documentation or books about this topic that I should read, I would really appreciate it.

Thanks,

Patrick


Okay so thanks to QuantumMechanic's link I managed to find the problem: http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

I just forgot my basics in linux programming, more importantly how program end is handled.

Basically, I needed to generate the syscall interrupt "exit" to handle the end of the program.

[BITS 32]

[global _start]
[extern main]

_start:
  call main
  mov ebx, eax  ; Move the returned value in the register used as argument of exit()
  mov eax, 1    ; Indicates the id of the syscall to execute
  int 0x80      ; Triggers the syscall interrupt

So now I can compile any C++ program on linux using my own RTL to make some tests.

Note that it won't be needed in the kernel should the end of the "main" function never be reached.

Thanks !


If you're willing to use a small (200K) portion of gcc's install, you can link in libgcc_s. This will give you all the code you need to have your program do static init and call main.


When you're building a kernel, you'll have to consider how it starts. Typically that's the bootloader's responsibility, and they're far from standard. It's certainly unlike starting Linux apps. Therefore it's not really sensible to worry too much about _start when you're going to ignore that way of starting anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜