"relocation R_X86_64_32S against `.bss' can not be used when making a shared object”

ove*_*low 5 linux assembly x86-64 nasm linker-errors

I'm absolutely green in this but during classes, teacher gave us file he wrote just for us to run it and it worked fine then, but when I try to do it at home (I use Linux on VirtualBox) and use:

nasm -f elf64 hello.asm -o hello.o
gcc hello.o -o hello
Run Code Online (Sandbox Code Playgroud)

I get an error "relocation R_X86_64_32S against `.bss' can not be used when making a shared object; recompile with -fPIC”. Can someone please explain what to do to make it work?

global main
extern printf

section .data
napis:      db ' Hello world! - po raz %ld',10,0

liczba_iteracji: equ 5

section .bss
licznik: resb 1

section .text

main:

push    rbp
mov rbp,rsp

mov byte [licznik],0

petla:              ;naiwna!

inc byte [licznik]

mov rdi, qword napis
mov rsi, qword [licznik]
mov rax, 0
call    printf

cmp byte [licznik],liczba_iteracji
jnz petla

mov rsp,rbp
pop rbp

mov rax,1           ;SYS_EXIT
mov rbx,0
int 80h
Run Code Online (Sandbox Code Playgroud)

Mic*_*kis 2

您需要确保您正在编写与位置无关的代码。PIC 的想法是,要使代码真正与位置无关,您至少需要一层间接。该级别的间接寻址是 IP 相对寻址,当这还不够时,您将需要第二层,即全局偏移表或 GOT。

在 NASM 中,您会发现DEFAULT REL指令很有用。