Calling C-functions from assembly

Discussion in 'Mac Programming' started by Flybro, Feb 19, 2010.

  1. Flybro macrumors newbie

    Joined:
    May 21, 2009
    Location:
    Down Under
    #1
    Hi,

    I'm trying to compile small assembly routine (nasm) which print a message to the console using the puts c-function.
    Unfortunately every time I try to compile it, I get "undefined symbol". If I replace "puts" with "_puts" then program compile without any errors or warnings but when I try run it "segementation fault" occurs.
    Code:
    nasm -f macho eatclib.asm
    gcc -arch i386 -o eat eatclib.o
    
    Undefined symbols:
      "puts", referenced from:
          _main in eatclib.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status
    
    Code:
    [SECTION .data]
    	
    	EatMsg: 		db "Eat at Joe's!",0	
    	
    [SECTION .bss]
    		
    [SECTION .text]
    	
    	extern puts
    	global _main
    	
    _main:
    	push	ebp
    	mov	ebp,esp
    	push	ebx
    	push	esi
    	push	edi
    	push	EatMsg
    	call	puts
    	add 	esp,4
    	pop 	edi
    	pop 	esi
    	pop 	ebx
    	mov 	esp,ebp
    	pop 	ebp
    	ret
    Code:
    gcc -v
    
    Using built-in specs.
    Target: i686-apple-darwin10
    Configured with: /var/tmp/gcc/gcc-5646.1~2/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10
    Thread model: posix
    gcc version 4.2.1 (Apple Inc. build 5646) (dot 1)
    
     
  2. Sydde macrumors 68020

    Sydde

    Joined:
    Aug 17, 2009
  3. autorelease macrumors regular

    Joined:
    Oct 13, 2008
    Location:
    Achewood, CA
    #3
    The reason why "call puts" doesn't work is probably because nasm doesn't understand GCC's name mangling. (All functions in libc actually have underscores before their names.) "call _puts" should work, but I don't remember enough x86 assembly to figure out why you're getting a segfault. :p

    Yes, puts does return an int, but it's in eax, so that shouldn't have any effect.

    Also, if you don't want to use nasm, assembly files can be passed right into GCC, and you won't have to worry about name mangling issues. Use the .S extension (capital S, that's important.) GCC will link everything together properly. Example:
    Code:
    gcc -o output file1.c file2.c file3.S
    You'll have to use AT&T syntax, but if I recall correctly there's some switch that lets you use Intel syntax.
     

Share This Page