c++ - 混合 C 和汇编文件

标签 c++ c gcc assembly x86

我想使用 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/

相关文章:

c - 基本C程式设计错误

c++ - 使用 openGL (C++) 放大/缩小的方法

c++ - CWinAppEx 未定义类

c - 对字符串数组中的单词进行排序

c++ - 我不明白C++指针算法

linux - Fedora 下 Firefox 未加载 XPCOM 组件

c - 在 Linux 上从 #include 生成 GCC 选项

c++ - C++将字符串转换为int

C++ 构建器模式插入运算符 `<<` 样式

无法使用 ARM NEON 内在函数设置 4 个 floatx32 的 vector