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.
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.
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.
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 Module
s from them), but the advantage is that it enables inlining and other cross-function optimizations from your JITted code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With