混合C和装配文件 [英] Mixing C and Assembly files

查看:122
本文介绍了混合C和装配文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

请告诉我,如果你知道任何。请注意,我不是在询问内联汇编,但链接C和汇编文件和方法来声明C的汇编中的extern变量,反之亦然,除了在C或汇编中使用它们之外,还有方法使用Makefile链接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();
}

在nakedasm文件中,对于x86:

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,并且运行:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆