How to link a C object file with a Assembly Language object file?

大憨熊 提交于 2019-11-30 12:42:20

ld -melf_i386 -e main main2.o strlength.o -o test

Don't do that. Do this instead:

gcc -m32 main2.o strlength.o -o test

(You should probably not call your test exectuable test, as it may conflict with the /bin/test, standard on most UNIX systems.)

Explanation: UNIX binaries do not generally start executing at main. They start executing in a function called _start, which comes from crt1.o or similar ("C Runtime startup"). That file is part of libc, and it arranges for various initializations, required for the proper start up of your application.

Your program actually doesn't require anything from libc, which is why you were able to link it with ld.

However, consider what happens after your main returns. Normally, the code in crt1.o will execute (equivalent of) exit(main(argc, argv));. Since you linked without crt1.o, there is nobody to do that final exit for you, so the code returns to ... undefined location and promptly crashes.

You also need to link the crt1.o (might have a different name, contains the necessary code up until main can be called) and necessary libraries. GCC also usually needs to link to libgcc.so which contains necessary helper functions (for example, when doing 64 bit calculations on a 32 bit system) plus other system libraries. For example, on my Mac, it also needs to link to libSystem which also contain the usual C functions like printf. On Linux, that's usually libc.

Note that your program cannot directly start with main (as you're trying to do with with ld .. -e main), the entry point needs to set up a few things prior to calling the C function main. That's what the previously mentioned crt1.o is doing. I guess the segmentation fault is a result of this missing setup.

To see what GCC is exactly doing on your system, call:

gcc main2.c strlength.s -m32 -o test -v
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!