5

I tried to create a library and test it, but an error occurred.
error code:

./libasm.a: error adding symbols: Archive has no index; run ranlib to add one
collect2: error: ld returned 1 exit status

I compiled it like this.
nasm -f macho64 ft_strlen.s -o ft_strlen.o
ar rcs libasm.a ft_strlen.o
ranlib libasm.a
gcc main.c libasm.a
Below is the source file

;ft_strlen.s
segment .text
    global ft_strlen

ft_strlen:
    mov     rax, 0
    jmp     count

count:
    cmp     BYTE [rdi + rax], 0
    je      exit
    inc     rax
    jmp     count

exit:
    ret
/*main.c*/
#include <stdio.h>

int ft_strlen(char *str);

int main(void)
{
    char *str = "hello world";
    printf("%d \n", ft_strlen(str));
}

I am using ubuntu installed on wsl.
What am I doing wrong?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
AMATEUR_TOSS
  • 256
  • 5
  • 13
  • 4
    `macho64` is for MacOS. Use `-f elf64` for Linux (including on WSL). Not sure if that's your only problem or not; most people don't add their `.o` files to static libraries, they just link them normally like `gcc -fno-pie -no-pie -g main.c ft_strlen.o`. – Peter Cordes Mar 20 '20 at 06:38
  • 2
    code review: Use `.s` for files that GAS can assemble, like `gcc -S` output. Use `.asm` for NASM source (which you *can't* run GCC on directly). Also, `jmp count` is pointless - execution will fall through into the loop without a `jmp`. You could rotate your loop to put the conditional branch at the bottom like normal idiomatic assembly code, then `jmp` to that branch condition to start the loop with the check before the increment. Or just start with `rax=-1` and let the first increment run to make it `0`. – Peter Cordes Mar 20 '20 at 06:44

1 Answers1

3

Generate object files for Linux-based operating system (or perhaps more correctly, and ELF64 system) with nasm -f elf64 ft_strlen.s -o ft_strlen.o

For more info nasm -hf to see all valid output formats for nasm -f

Small tip: ranlib command is not needed because ar s is already indexing the library.

AMATEUR_TOSS
  • 256
  • 5
  • 13