LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Linking assembly and C (https://www.linuxquestions.org/questions/programming-9/linking-assembly-and-c-805044/)

gozlemci 04-29-2010 03:34 PM

Linking assembly and C
 
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;
}

Original code is in http://www.cs.lmu.edu/~ray/notes/nasmexamples/ but it only mentions how to link in windows, but it did not mention linux. I've asked it to google, but no reply.
I am using ubuntu 9.10 and my NASM version 2.05.01 compiled on Nov 5 2008.

Any help is greatly appreciate.

smeezekitty 04-29-2010 03:36 PM

nasm <assembly>.s -o asm.o
gcc <cfile>.c -c -o cfile.o
ld cfile.o asm.o -lgcc -lc -lm -o output

smeezekitty 04-29-2010 03:37 PM

Oh and for portability sake, cmov should be replaced my a mov/jmp/cmp construct.

johnsfine 04-29-2010 03:40 PM

Quote:

Originally Posted by gozlemci (Post 3952297)
I have a C code and assembly (nasm) code and I am not able to find how to link them each other.

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.

gozlemci 04-29-2010 03:46 PM

Thank you everybody again. Another good reason to use Linux :) Yaşasın Linux :)


All times are GMT -5. The time now is 11:15 PM.