GCC-Assemby Error: Relocation R_X86_64_32S against '.data'

GCC-Assemby Error: Relocation R_X86_64_32S against '.data'

情况


  1. 环境

    Arch Linux x86-64 (4.2.3-1-ARCH)

  2. 海湾合作委员会

    gcc (GCC) 5.2.0

  3. 命令

    gcc -Wall -g -o asm_printf asm_printf.s 
    
  4. 错误

    /usr/bin/ld: /tmp/cct4fa.o: Relocation R_X86_64_32S against '.data' can not be used when making a shared object; recompile with -fPIC
    /tmp/cct4fa.o:err adding symbols: Bad value
    collect2: error: ld returned 1 exit status
    
  5. 代码

    .section .data
    msg:
        .asciz "Printf In Assembly!!\n"
    
    .section .text
    .globl main
    main:
        pushq $msg
        call printf
        addq  %esp
    
        pushq [=12=]
        call exit
    

问题


我尝试使用gcc编译上面Code部分的程序,使用上面Command中的命令部分并以 Error 部分中的错误结束。

Note that I am not compiling a shared library.

  1. 这是什么错误?
  2. 我该如何解决这个问题?

特定错误是由于 push 指令仅支持 32 位立即数而您试图将其用于 64 位地址。

然而,整个代码是错误的。目前尚不清楚您需要 32 位还是 64 位代码。大多数代码似乎是 32 位的,除了 pushq 所以我假设你真的想要 32 位代码。为此,将所有这些更改为 push(无论如何这是一个好主意)并使用 gcc -m32 进行编译。另外,你只需要从堆栈中删除 4 个字节,所以使用 addl , %esp。 (感谢 @Employed Russian 指出这一点。)

64 位调用约定与 32 位不同,因此要创建 64 位版本,您必须进行更多更改。因为我假设你真的想要 32 位,这里仅供说明:

.section .data
msg:
    .asciz "Printf In Assembly!!\n"

.section .text
.globl main
main:
    subq , %rsp
    leaq msg(%rip), %rdi
    xor %al, %al
    call printf

    xor %edi, %edi
    call exit