Skip to content
Advertisement

Calling assembly routines from C source code

I have this simple C source code :

#include <stdio.h>

extern int Sum(int,int);

int main()
{
  int a,b,s;
  a=1 , b=2;
  s = Sum(a,b);
  return 0;
}

and i have this s.asm which defines the function _Sum :

global _Sum

     _Sum:

        push    ebp             ; create stack frame
        mov     ebp, esp
        mov     eax, [ebp+8]    ; grab the first argument
        mov     ecx, [ebp+12]   ; grab the second argument
        add     eax, ecx        ; sum the arguments
        pop     ebp             ; restore the base pointer
        ret

now , i compiled the .asm using :

nasm s.asm -f elf -o s.o

and compiled and linked the .c file using :

gcc s.o test.o -o testapp

this is the outcome :

/tmp/ccpwYHDQ.o: In function `main':
test.c:(.text+0x29): undefined reference to `Sum'
collect2: ld returned 1 exit status

So what is the problem ?

I’m using Ubuntu-Linux

Any help would be greatly appreciated , Thanks

[SOLVED] : i checked with nm the test.o file and it expected to find the symbol ‘Sum’ not ‘_Sum’ so changing that solved the problem.

Advertisement

Answer

As far as I can see from your question, you overwrite your object file that came from the assembler s.o by the C program. So you don’t have the assembler routine any more.

You should probably write

Generate the s.o object file

 nasm s.asm -f elf -o s.o

Generate the test.o (your command created another s.o)

 gcc test.c -c 

Link the app

 gcc s.o test.o -o testapp 

(I chose testapp as output binary because test is often a very bad name for a program, it collides with the Unix command test)

Advertisement