混合C和汇编文件

Met*_*est 8 c c++ x86 assembly gcc

我想使用g ++在我的C++程序中使用裸函数.不幸的是,与VC++不同,g ++不支持裸函数,管理它的唯一方法是在单独的文件中编写自己的汇编代码并与C++文件链接.我试图找到一些很好的x86教程来混合汇编和C/C++文件,但找不到任何好的.

如果您知道任何问题,请告诉我.请注意,除了在C或程序集中使用它们之外,我不是要求内联汇编而是链接C和汇编文件以及在汇编中声明C的外部变量的方法,反之亦然,以及使用Makefile链接C和asm文件的方法.

Fle*_*exo 17

在C++文件中:

extern "C" void foo(); // Stop name mangling games

int main() {
  foo();
}
Run Code Online (Sandbox Code Playgroud)

在"裸"的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
Run Code Online (Sandbox Code Playgroud)

编译,汇编和链接(用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!
Run Code Online (Sandbox Code Playgroud)

如果要将参数传递给函数或返回任何需要遵守调用约定的内容.


chi*_*ill 5

这是一个实现"裸功能"效果的技巧示例.

#include <stdio.h>

extern "C" int naked_func ();

static void
dummy ()
{
  __asm__ __volatile__
    (
     "  .global naked_func\n"
     "naked_func:\n"
     "  movq    $3141569, %rax\n"
     "  ret\n"
     );
}

int
main ()
{
  printf ("%d\n", naked_func ());
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 您甚至不需要将虚函数作为包装器,因为基本内联汇编可以放在全局范围内. (2认同)