从 gcc 编译的汇编代码不是 运行

Assembly code compiled from gcc not running

今天,我决定做一个(非常)简单的OS。我不想直接使用汇编,因为我觉得它对我来说太乱了。但是,我知道一点 C,我渴望学习更多。我做了一个简单的程序来打印一个字符串,我想把它编译成程序集。我用这个命令编译成程序集:

gcc -S foo.c

这是我的 C 代码:

#include<stdio.h>

int main() {
        printf("Hi!!!");
}

但是当我尝试 运行 输出文件 (foo.s) 时,我得到了这些错误:

foo.s:1: error: parser: instruction expected
foo.s:2: warning: label alone on a line without a colon might be in error [-w+label-orphan]
foo.s:3: error: parser: instruction expected
foo.s:5: error: parser: instruction expected
foo.s:6: warning: label alone on a line without a colon might be in error [-w+label-orphan]
foo.s:7: error: parser: instruction expected
foo.s:8: error: parser: instruction expected
foo.s:11: warning: label alone on a line without a colon might be in error [-w+label-orphan]
foo.s:12: error: parser: instruction expected
foo.s:13: error: parser: instruction expected
foo.s:14: error: parser: instruction expected
foo.s:15: error: expression syntax error
foo.s:16: error: parser: instruction expected
foo.s:17: error: parser: instruction expected
foo.s:18: error: parser: instruction expected
foo.s:20: error: label `movl' inconsistently redefined
foo.s:18: info: label `movl' originally defined here
foo.s:20: error: parser: instruction expected
foo.s:21: error: parser: instruction expected
foo.s:22: error: parser: instruction expected
foo.s:24: warning: label alone on a line without a colon might be in error [-w+label-orphan]
foo.s:26: error: parser: instruction expected
foo.s:27: error: parser: instruction expected
foo.s:28: error: parser: instruction expected

这是我运行编译汇编代码的命令:

nasm -f bin -o foo.bin foo.s

这是foo.s中的汇编代码:

        .file   "foo.c"
        .text
        .section        .rodata
.LC0:
        .string "Hi!!!"
        .text
        .globl  main
        .type   main, @function
main:
.LFB0:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        leaq    .LC0(%rip), %rdi
        movl    [=14=], %eax
        call    printf@PLT
        movl    [=14=], %eax
        popq    %rbp
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE0:
        .size   main, .-main
        .ident  "GCC: (Debian 10.2.1-6) 10.2.1 20210110"
        .section        .note.GNU-stack,"",@progbits

有人请帮助我!

gcc 输出不使用 NASM 语法。您应该使用 as 将其 assemble 放入目标文件中,然后 link 与标准库一起使用:

> as -o foo.o foo.s
> gcc foo.o # Link
> ./a.out
Hi!!!