1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Linking assembly and C

Discussion in 'C++' started by inspiration, May 27, 2010.

  1. inspiration

    inspiration New Member

    Joined:
    Feb 15, 2010
    Messages:
    85
    Likes Received:
    0
    Trophy Points:
    0
    Hi everybody;
    I have a C code and assembly (nasm) code and I am not able to find how to link them each other. Here are the codes :
    NASM side:
    Code:
    global	_maxofthree
    	
    	section .text
    _maxofthree:
    	mov	eax, [esp+4]
    	mov	ecx, [esp+8]
    	mov	edx, [esp+12]
    	cmp	eax, ecx
    	cmovl	eax, ecx
    	cmp	eax, edx
    	cmovl	eax, edx
    	ret
    C Side:
    Code:
    int maxofthree(int , int , int );
    
    #include <stdio.h>
    
    int main() {
    
        printf("%d\n", maxofthree(1, -4, -7));
        printf("%d\n", maxofthree(2, -6, 1));
        printf("%d\n", maxofthree(2, 3, 1));
        printf("%d\n", maxofthree(-2, 4, 3));
        printf("%d\n", maxofthree(2, -6, 5));
        printf("%d\n", maxofthree(2, 4, 6));
        return 0;
    }
    Any help is greatly appreciate.
     
  2. pankaj.sea

    pankaj.sea New Member

    Joined:
    Apr 6, 2009
    Messages:
    461
    Likes Received:
    13
    Trophy Points:
    0
    Occupation:
    Web Developer
    Location:
    Kolkata
    Home Page:
    nasm <assembly>.s -o asm.o
    gcc <cfile>.c -c -o cfile.o
    ld cfile.o asm.o -lgcc -lc -lm -o output
     
  3. pankaj.sea

    pankaj.sea New Member

    Joined:
    Apr 6, 2009
    Messages:
    461
    Likes Received:
    13
    Trophy Points:
    0
    Occupation:
    Web Developer
    Location:
    Kolkata
    Home Page:
    Oh and for portability sake, cmov should be replaced my a mov/jmp/cmp construct.
     
  4. meyup

    meyup New Member

    Joined:
    Feb 15, 2010
    Messages:
    102
    Likes Received:
    0
    Trophy Points:
    0
    It is a lot easier if you let gcc invoke the linker for you.

    Code:
    nasm -felf32 asm_name.asm
    gcc -m32 c_name.c asm_name.o -o program_name
    If you are running 32 bit Linux, the -m32 is not needed (but it shouldn't do any harm).

    If you are running 64 bit Linux, the -m32 is needed and various 32 bit support files might need to be installed before it will work.
     
  5. inspiration

    inspiration New Member

    Joined:
    Feb 15, 2010
    Messages:
    85
    Likes Received:
    0
    Trophy Points:
    0
    Thank you everybody!
    thanks a lot!
    :D
     

Share This Page