Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call C/C++ functions from the ExecutionEngine

Tags:

llvm

I am learning llvm and wanted to do a proof of concept of an idea I have.

Basically, I want to split my compiler and my runtime. The compiler would give a .bc and the runtime would load it via ParseBitcodeFile and use the ExecutionEngine to run it. This part is working.

Now, to make system calls easily, I want to be able to implement in my runtime C/C++ functions which do all the system calls (file io, stdout printing, etc). My question is, how could I call these functions from the code from my toy compiler, which is compiled in a different step by llvm, and allow it to be used when executed.

like image 643
FrankBro Avatar asked Jul 11 '13 03:07

FrankBro


People also ask

How will you call C functions from C ++ and vice versa?

Just declare the C function extern "C" (in your C++ code) and call it (from your C or C++ code). For example: // C++ code. extern "C" void f(int); // one way.

Can we call CPP function from C?

Accessing C++ Code from Within C SourceIf you declare a C++ function to have C linkage, it can be called from a function compiled by the C compiler. A function declared to have C linkage can use all the features of C++, but its parameters and return type must be accessible from C if you want to call it from C code.


1 Answers

Eli's answer is great and you should accept it. There's another alternative, though, which is to separately compile your runtime's source files to LLVM modules (e.g. with Clang) and use ExecutionEngine::addModule() to add them.

It's less convenient, and it means compiling the same files twice (once for your host program, another to get Modules from them), but the advantage is that it enables inlining and other cross-function optimizations from your JITted code.

like image 135
Oak Avatar answered Nov 09 '22 09:11

Oak