@include _ext.texi @node C FFI @chapter C FFI O programming language follows C's calling conventions, meaning that every O function can be called by C without any extra effort. All example bellow will use @code{gcc} but you can use the compiler/linker of your preference. @section Calling C from O To call external code you can use the @code{extern} statement. @subsection extern @sethl olang @verbatim # file: answer.ol extern fn u32print(number: u32): u32 fn main(): u8 { u32print(42) return 0 } @end verbatim That way instead of defining the @code{u32print} function. It must be provided at the linkage step. @sethl c @verbatim // file: u32print.c #include int u32print(int number) { return printf("%d\n", number); } @end verbatim @subsection Compiling without linking If you try to compile the answer.ol file by using the @code{olc answer.ol -o answer.o} command you will receive the follow error: @sethl- output @verbatim /usr/bin/ld: answer.o.o: in function `main': (.text+0x10): undefined reference to `u32print' collect2: error: ld returned 1 exit status @end verbatim That's because @code{O} tries to link by default. To assemble the code without linking it, you can use the @code{-c} option. @sethl- bash @verbatim olc answer.ol -c -o answer.o @end verbatim After that you can do the same with the C file that contains the function that you are looking to call. @sethl- bash @verbatim gcc u32print.c -c -o u32print.o @end verbatim And then you can link both object files into an executable: @sethl- bash @verbatim gcc answer.o u32print.o -o answer @end verbatim @subsection Calling O from C All that is required is to set the function prototype. @sethl olang @verbatim # file: sum.ol fn sum(a: u32, b: u32): u32 { return a + b } @end verbatim @sethl c @verbatim // file: csum.c #include int sum(int a, int b); int main() { printf("%d\n", sum(41, 1)); return 0; } @end verbatim Compiling: @sethl- bash @verbatim olc sum.ol -c -o sum.o gcc sum.o csum.c -o csum @end verbatim