How do I call an external function from C?

Calling an external Assembly function from C

Page 1 of 1

2 Replies - 605 Views - Last Post: 09 December 2012 - 06:06 PM Rate Topic: -----

#1 carnivroar  Icon User is offline

  • D.I.C Regular

Reputation: 28
  • View blog
  • Posts: 384
  • Joined: 18-September 11

How do I call an external function from C?

Posted 14 November 2012 - 04:29 PM

Can anyone help me get this working?

$ nasm -f elf64 -o factorial.o factorial.asm

$ g++ -c test.cpp -o test.o

$ g++ -o TEST factorial.o test.o
test.o: In function `main':
test.cpp:(.text+0xa): undefined reference to `factorial(int)'
collect2: ld returned 1 exit status

#include <iostream>
using namespace std;

extern long factorial(long);

int main() {
    cout << factorial(20);
    return 0;
}



global factorial

factorial:
   xor    rbx, rbx
   add    rbx, $1
   xor    rdi, rdi
   add    rdi, [esp+4] 
fact:           
   xor    rax, rax
   add    rax, rdi 
   mul    rbx 
   xor    rbx, rbx
   add    rbx, rax 
   dec    rdi 
   cmp    rdi, $1 
   jg     fact  
   xor    rax, rax
   add    rax, rbx 
   ret



Thanks! :)

Is This A Good Question/Topic? 0
  • +

Replies To: How do I call an external function from C?

#2 GunnerInc  Icon User is offline

  • "Hurry up and wait"
  • member icon




Reputation: 859
  • View blog
  • Posts: 2,308
  • Joined: 28-March 11

Re: How do I call an external function from C?

Posted 14 November 2012 - 07:09 PM

*** Split from tutorial - Calling assembly routines from C
Was This Post Helpful? 0
  • +
  • -

#3 carnivroar  Icon User is offline

  • D.I.C Regular

Reputation: 28
  • View blog
  • Posts: 384
  • Joined: 18-September 11

Re: How do I call an external function from C?

Posted 09 December 2012 - 06:06 PM

extern "C" long factorial(long*);

in case anyone needs it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1