0

On mac OS(which has intel inside), I tried to make a simple x86 hybrid program with main module written in C and a function written in x86 assembly language (NASM assembler).

Then, the following function is to reverse the string of the argument.

My C code is

#include <stdio.h>
char *revstring(char *s);
int main(int argc, char* argv[]){
for (int i=1; i<argc; i++){
    printf("%s->", argv[i]);
    printf("%s\n", revstring(argv[i]));
    }
}

Then my assembly code

section .text
    global revstring
revstring:
    push    rbp
    mov     rbp, rsp
    mov     rax, [rbp+8]
    mov     rcx, rax
find_end:
    mov     dl, [rax]
    inc     rax
    test    dl, dl
    jnz     find_end
    sub     rax, 2
    
swap:
    cmp     rax, rcx
    jbe     fin
    
    mov     dl, [rax]
    xchg    dl, [rcx]
    mov     [rax], dl
    dec     rax
    inc     rcx
    jmp     swap

fin:
    mov     rax, [rbp+8]
    pop     rbp
    ret

Currnt MacOS cannot run 32 bit program, so I built the program by using these commands.

cc -m64 -std=c99 -c revs.c
nasm -f macho64 revstring.s
cc -m64 -o revs revs.o revstring.o

But the following error occured.

Undefined symbols for architecture x86_64:
"_revstring", referenced from:
    _main in revs.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 

I cannot find any solutions, so could anyone help me?

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • 2
    Your function is named `revstring`. The compiler is looking for `_revstring`. – Raymond Chen May 06 '22 at 14:50
  • 1
    Some systems have the convention that any variable or function defined or referenced in C source is translated to a symbol with an underscore prepended. This is apparently the case on MacOS. No such automatic translation is done on assembly sources, so your assembly code has to explicitly name its function as `_revstring`. – Nate Eldredge May 06 '22 at 15:07
  • Just FYI, `xchg dl, [rcx]` is *very* slow: atomic RMW with a full memory barrier, since `xchg` with memory has an implicit `lock` prefix, unfortunately. (Since 386). – Peter Cordes May 06 '22 at 15:27

0 Answers0