0

When i try to link my assembly program ld linker says

undefined reference to printf

I tried writing extern printf in my code but gnu assembler says no such instruction.

my code is

.section .data
Dd: .ascii "hello"

.section .text
.global _start
_start:
.global main
main:
    movq $0, %rax
    movq $Dd, %rdi
    call printf
    ret
    movq $60, %rax
    syscall

Linker say undefined reference to 'printf'

Even i tried to link -dynamic-linker /lib/ld-linux.so.2

  • How do you assemble and link your program? – fuz May 14 '20 at 17:43
  • 1
    `printf` is in libc. Use `gcc hello.S` to assemble and link your program with libc and CRT start code that will call your `main`. There's no point in using `ld` directly unless you're writing your own `_start`. – Peter Cordes May 14 '20 at 17:44
  • as hello.s -o hello.o && ld -o hello hello.o, – imComputerGeek May 14 '20 at 17:45
  • But how to do it if i write my own _start: – imComputerGeek May 14 '20 at 17:47
  • Should be the same - your `_start:` should take precedence over the one from the C runtime. Did you try it? – Carl Norum May 14 '20 at 17:50
  • Almost a duplicate of [Linking a C program directly with ld fails with undefined reference to \`\_\_libc\_csu\_fini\`](https://stackoverflow.com/q/6656317) which explains linking a normal `main` like a C compiler might produce, using `ld`. – Peter Cordes May 14 '20 at 17:51
  • @CarlNorum: No, your own `_start` will *conflict with* CRT start code if you link it. If you write your own `_start`, assemble + link with `gcc -no-pie -nostartfiles` or `gcc -no-pie -nostdlib`. – Peter Cordes May 14 '20 at 17:53
  • I just tried it here - no problems on my test. It's a mac, though, so the linker behaviour might be different. – Carl Norum May 14 '20 at 17:54
  • Actually my test might be bad - looks like `start` isn't what I think it's labeled. – Carl Norum May 14 '20 at 17:55
  • @imComputerGeek: Writing your own `_start` is different from writing your own `main`, even in terms of how you build an executable out of it. So that would be a separate question. [Linker error when calling printf from \_start](https://stackoverflow.com/q/39557237) – Peter Cordes May 14 '20 at 18:01

0 Answers0