vishapoberon / compiler

vishap oberon compiler
http://oberon.vishap.am
GNU General Public License v3.0
186 stars 25 forks source link

External libs / Foreign function interface #58

Open dasannikov opened 7 years ago

dasannikov commented 7 years ago

Is any way to link with existing lib (static or dynamic)? May be some foreign function interface (with C support)?

dasannikov commented 7 years ago

After some investigation I have found that I can declare foreign C function. PROCEDURE -MyFunc*(a: INTEGER): INTEGER "func(a)"; But how can I implement and/or link it using voc.

Maybe something like voc func.c main.mod -m will pass C file to C compiler/linker.

dasannikov commented 7 years ago

Finally did it. Compile and link output C files (from oberon) + my C files with gcc. It will be good to have instruction for future users.

antranigv commented 7 years ago

@dasannikov may you show an exaple? :)

dasannikov commented 7 years ago

So, You can create Module like this

MODULE MyModule;

IMPORT SYSTEM;
(* include header *)
PROCEDURE -AincludeMyHeader* '#include "MyHeader.h"';
(*add function*)
PROCEDURE -MyFunction*(a:INTEGER): INTEGER "MyFunction(a)";
BEGIN
END MyModule.

And translate it using voc to c files (do not compile and link it) You will have 2 files - MyModule.h and MyModule.c

Additionally you will need C header MyHeader.h

#define INTEGER  INT32
#include <SYSTEM.h>
import INTEGER MyFunction(INTEGER a);

And MyHeader.c - implementation file.

#define INTEGER  INT32
#include <SYSTEM.h>
INTEGER func(INTEGER a) {
    return a / 2;
}

Then you compile an link all this files with GCC/CLANG. It's a little bit complicated because of many params (includes and libs). But here is part of my Makefile if it helps.

all: test01

test01: mymod.c main.c
    clang -g -std=c1x -o3 mylib.c main.c mymod.c -otest01 -I"/GitHub/oberon-voc/install/2/include" -L"/GitHub/oberon-voc/install/lib" -lvoc-O2

main.c: main.mod
    voc -OC -S main.mod -m

mymod.c: mymod.mod
    voc -OC -S -s mymod.mod