26

gcc 可以生成程序集,但是如何使用 gcc 或其他编译器编译纯程序集?我知道 x86 汇编很困难,并且是另一个指令集,而不是我正在查看的 MIPS 和 Nios,但现在我想尝试直接编译 x86 asm。有如何做到这一点的说明,但其中包含一个 C 文件,我的第一个最基本的编译不需要 C 文件。

gcc -o test_asm asm_functions.S test_asm.c

有创建.o文件的步骤

gcc -c asm_functions.S
gcc -c test_asm.c
gcc -o test_asm asm_functions.o test_asm.o

但是我没有看到可以直接用 gcc 编译 x86 asm 的步骤。还有一个名为GNU as (GNU Assembler)的程序,它可以用来将x86汇编翻译成机器码吗?

测试

代码 (32.s)

.globl  _start

.text
_start:
        movl    $len, %edx
        movl    $msg, %ecx
        movl    $1, %ebx
        movl    $4, %eax
        int     $0x80

        movl    $0, %ebx
        movl    $1, %eax
        int     $0x80
.data
msg:
        .ascii  "Hello, world!\n"
        len =   . - msg

脚步

$ gcc -c 32.s 
$ ls 32*
32.o  32.s
$ gcc -o 32 32.o 
32.o: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'

所以看起来它可能混合了 32 位和 64 位,我必须告诉编译器程序集是 32 位还是 64 位指令吗?

更新

该测试适用于 gcc。

$ cat hello.s
.data
.globl hello
hello:
.string "Hi World\n"

.text
.global main
main:
    pushq   %rbp
    movq    %rsp,       %rbp
    movq    $hello,     %rdi
    call    puts
    movq    $0,         %rax
    leave
    ret
$ gcc hello.s -o hello
$ ./hello 
Hi World
4

2 回答 2

20

你已经在做。

gcc -c asm_functions.S

该步骤会生成一个目标文件asm_functions.o. 目标文件是“可链接”(相对于“可加载”)文件,其中包含机器代码,并附有一些关于链接器在链接时应如何修改代码的额外说明。gcc程序本身只是一个驱动程序,它as在幕后运行,供您制作asm_functions.o。因此,您确实可以选择直接运行,但通常运行前端as更容易。gcc

于 2013-02-18T06:49:38.043 回答
3

尽管更新有效,但原始代码可以通过简单地使用gcc -nostdlib. 例如,

gcc -nostdlib 32.s -o 32
于 2016-07-07T18:10:35.853 回答