简体   繁体   English

在Mac OS X上组装和链接gcc生成的程序集

[英]Assembling and Linking gcc generated assembly on Mac OS X

If I have the following C Code 如果我有以下C代码

int main()
{
    return 77;
}

I can generate asm code with the -S option on clang to get the following (Intel syntax) 我可以使用clang上的-S选项生成asm代码以获取以下内容(Intel语法)

$clang -O0 -mllvm --x86-asm-syntax=intel main.c -S 

the code then is 那么代码就是

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    push    RBP
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset rbp, -16
    mov RBP, RSP
Ltmp4:
    .cfi_def_cfa_register rbp
    mov EAX, 77
    mov DWORD PTR [RBP - 4], 0
    pop RBP
    ret
    .cfi_endproc


.subsections_via_symbols

However neither as, gas or nasm will generate an object file to link with ld... does clang or gcc generate actual good "ready to go" asm? 然而,无论是gas还是nasm都会生成一个目标文件来链接ld ... clang或gcc会产生实际的好“准备好去”asm吗? gcc's default assembler is gas (which isn't even installed on mac os x...? isn't it the same for clang). gcc的默认汇编程序是gas(甚至没有安装在mac os x上......?对于clang来说不一样)。

So how do I manually assemble the asm code and then link it? 那么如何手动组装asm代码然后链接呢?

  1. Yes, gcc generates correct assembly code. 是的,gcc生成正确的汇编代码。

  2. It's just as . 这只是as

  3. You should be able to assemble it with as and link with ld : 你应该能够用as组装它并与ld链接:

     as -o example.o example.s ld -macosx_version_min 10.8.0 -o example example.o -lSystem 

    or, probably more easily, by using gcc or clang as the frontend: 或者,可能更容易,使用gccclang作为前端:

     cc -o example example.s 

Edit: Complete working example: 编辑:完整的工作示例:

$ cat example.c 
int main()
{
    return 77;
}
$ gcc -S example.c -o example.s
$ as -o example.o example.s
$ ld -macosx_version_min 10.8.0 -o example example.o -lSystem
$ ./example 
$ echo $?
77

OK, since you're using clang, you might want to be using its assembler, too. 好的,既然你正在使用clang,你也可能想要使用它的汇编程序。 Mixing & matching toolchains usually ends in tears: 混合和匹配工具链通常以泪水结束:

$ clang -cc1as -filetype obj -mllvm --x86-asm-syntax=intel -o example.o example.s
$ ld -macosx_version_min 10.8.0 -o example example.o -lSystem

既然你正在使用clang,为什么不用clang而不是gcc编译呢?

clang main.s -mllvm --x86-asm-syntax=intel -o main

尝试使用.s文件调用gcc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM