1

Here is my issue, I try to create an assembly function library and use it with a C program. I run into an undefined reference error.

I use xubuntu on a vm, provided by school for this project (so I guess everything is well setup...)

Assembly file (ft_function.s)

section .text
    global _ft_function

_ft_function:
    mov rax, 42
    ret

C file (main.c)

extern int ft_function(char const *str);

int main()
{
    return (ft_function("abc"));
}

For now as the issue persists I don't create the library, to reduce everything the most simple situation, so I generate the object files, then link them with clang.

nasm -f elf64 ft_function.s -o ft_function.o
clang -c main.c

clang ft_function.o main.o

main.o: In function `main':
main.c:(.text+0x1a): undefined reference to `ft_function'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thanks for your help ! Cheers !

Bstorm
  • 247
  • 1
  • 10
  • You don't need a leading underscore on platforms other than MacOS, for x86-64. – Peter Cordes Jun 11 '20 at 15:24
  • Almost a duplicate of [Will the functions and variables precede with an "\_" when compiled using gcc?](https://stackoverflow.com/q/38272921) – Peter Cordes Jun 11 '20 at 15:33
  • Indeed, I'm sorry for posting duplicate question but not knowing the issue to start with makes it hard to find duplications of it. – Bstorm Jun 11 '20 at 16:18
  • No need to apologize; your question contained enough info to be fully answerable, it just happened that other people have had the same problem before. It's normal that finding duplicates is trivial for people that know the answer, but otherwise isn't. – Peter Cordes Jun 11 '20 at 16:23
  • I will point out that the error message contains a hint: `undefined reference to `ft_function'` doesn't have a leading underscore on the asm symbol name it mentions. But probably you assumed it was demangling the name for you. And you did know that leading underscore was a possible issue, so could have double-checked. As usual, with hindsight it's easy to point out lots of ways you might have solved it yourself, but IMO this one is not totally obvious (unlike some questions where single-stepping with a debugger and/or reading an instruction-set reference would have made a problem obvious.) – Peter Cordes Jun 11 '20 at 16:26

1 Answers1

1
section .text
    global _ft_function

_ft_function:
    mov rax, 42
    ret

Omit the leading underscores. Some other systems use symbol names starting with underscore, but Linux does not. Just do:

section .text
    global ft_function

ft_function:
    mov rax, 42
    ret
Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • Haa gosh I've been trying everything, including what you proposed, without success ! But it does work now, so I guess I probably tried the wrong combination of solutions when looking for a fix ! thank you so much ! – Bstorm Jun 11 '20 at 15:28