混合C和汇编文件 [英] Mixing C and Assembly files
问题描述
I want to use a naked function in my C++ program using g++. Unfortunately g++, unlike VC++, does not support naked functions and the only way to manage this is to write your own assembly code in a separate file and link with your C++ files. I tried to find some good tutorial for x86 to mix assembly and C/C++ files but couldn't find any good one.
请让我知道如果你知道任何。请注意,我不是问内嵌汇编,但联用的Makefile C和汇编文件,以及如何申报装配,反之亦然的C extern变量除了在C语言或汇编使用它们,并且还的方式到C链接和ASM文件
Kindly let me know if you know about any. Note that I'm not asking about inline assembly but linking C and assembly files and ways to declare extern variables of C in assembly and vice versa besides using them in either C or assembly, and also ways to link the C and asm files using Makefile.
推荐答案
在C ++文件:
extern "C" void foo(); // Stop name mangling games
int main() {
foo();
}
在裸体ASM文件,86:
in "naked" asm file, for x86:
# modified from http://asm.sourceforge.net/howto/hello.html
.text # section declaration
.global foo
foo:
# write our string to stdout
movl $len,%edx # third argument: message length
movl $msg,%ecx # second argument: pointer to message to write
movl $1,%ebx # first argument: file handle (stdout)
movl $4,%eax # system call number (sys_write)
int $0x80 # call kernel
# and exit
movl $0,%ebx # first argument: exit code
movl $1,%eax # system call number (sys_exit)
int $0x80 # call kernel
.data # section declaration
msg:
.ascii "Hello, world!\n" # our dear string
len = . - msg # length of our dear string
编译,汇编和链接(使用g ++而不是ld,因为它是很容易做的这种方式对于C ++),然后运行:
Compile, assemble and link (with g++ rather than ld because it's much easier to do it that way for C++) and run:
ajw@rapunzel:/tmp > g++ -Wall -Wextra test.cc -c -o test.o
ajw@rapunzel:/tmp > as -o asm.o asm.S
ajw@rapunzel:/tmp > g++ test.o asm.o
ajw@rapunzel:/tmp > ./a.out
Hello, world!
显然,如果你想将参数传递给你的函数或者返回任何你需要尊重的调用约定。
Clearly if you want to pass arguments to your function or return anything you need to respect the calling conventions.
这篇关于混合C和汇编文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!