无法使用gcc编译汇编语言的hello world程序

3

这是在hello.s中的代码。

.data                         

hello_str:                    
    .string "Hello, world!\n"


    .set hello_str_length, . - hello_str - 1

.text                         

.globl  main                  

.type   main, @function       


main:
    movl    $4, %eax      

    movl    $1, %ebx     

    movl    $hello_str, %ecx  

    movl    $hello_str_length, %edx 

    int     $0x80        

    movl    $1, %eax      
    movl    $0, %ebx      
    int     $0x80         

    .size   main, . - main   

我运行了gcc hello.s -o hello命令,但是出现了以下错误:

/usr/bin/ld: /tmp/cc6ILJpd.o: relocation R_X86_64_32 against '.data' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output

collect2: error: ld返回了1个退出状态

然后我尝试运行gcc hello.s -fPIC -o hello,但它没有做任何事情,错误是相同的。

我做错了什么?Ubuntu 17.04,GCC 6.3.0。

1个回答

2

您试图在amd64模式下编译i386代码,这是行不通的。请改为尝试以下步骤:

gcc -m32 hellos. -o hello

我想你需要强制使用 i386 模式。

编辑:我之所以能够识别这个问题,是因为我知道 i386 和 amd64 代码是什么样子的,但更好的线索在于重新定位名称R_X86_64_32。X86_64 是 amd64 架构的另一个名称;所以这意味着它是针对 X86_64 架构的 32 位重定位。考虑到你不是为该架构编写代码,这是一个合理的迹象,说明使用了错误的编译器。


1
另一个提示是 int 80h。64位模式应该使用 syscall(当然,参数不同)代替(虽然 int 80h 在当前内核上通常可以工作,但它可能会在未来的Linux内核中消失,因为它并非正式存在)。 - Ped7g

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接