我想使用 naked function在我的 C++ 程序中使用 g++。不幸的是,与 VC++ 不同,g++ 不支持裸函数,管理它的唯一方法是在单独的文件中编写您自己的汇编代码并链接到您的 C++ 文件。我试图找到一些很好的 x86 教程来混合汇编和 C/C++ 文件,但找不到任何好的教程。
如果你知道的话,请告诉我。请注意,我不是在询问内联汇编,而是链接 C 和汇编文件以及在汇编中声明 C 的外部变量的方法,反之亦然,除了在 C 或汇编中使用它们之外,还有使用 Makefile 链接 C 和 asm 文件的方法.
最佳答案
在 C++ 文件中:
extern "C" void foo(); // Stop name mangling games
int main() {
foo();
}
在“裸”asm 文件中,对于 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++ 来说这样做要容易得多)并运行:
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!
如果您想将参数传递给您的函数或返回您需要遵守调用约定的任何内容。
关于c++ - 混合 C 和汇编文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8054362/