Yan Zhou
Yan Zhou

Reputation: 2767

Compile a C++ function inside a C++ program

Consider the following problem,

A C++ program may emit source of a C++ function, for example, say it will create a string with contents as below:

std::vector<std::shared_ptr<C>> get_ptr_vec()
{
    std::vector<std::shared_ptr<C>> vec;
    vec.push_back(std::shared_ptr<C>(new C(val1)));
    vec.push_back(std::shared_ptr<C>(new C(val2)));
    vec.push_back(std::shared_ptr<C>(new C(val3)));
    vec.push_back(std::shared_ptr<C>(new C(val4)));
    return vec;
}

The values of val1 etc will be determined at runtime when the program create the string of the source above. And this source will be write to a file, say get_ptr_vec.cpp.

Then another C++ program will need to read this source file, and compile it, and call the get_ptr_vec function and get the object it returns. Kind of like a JIT compiler.

Is there any way I can do this? One workaround I think would be having a script that will compile the file, build it into a shared library. And the second program can get the function through dlopen. However, is there anyway to skip this and having the second program to compile the file (without call to system). Note that, the second program will not be able to see this source file at compile time. In fact, there will be likely thousands such small source files emitted by the first program.

To give a little background, the first program will build a tree of expressions, and will serialize the tree by traversing through postorder. Each node of tree will have a string representation written to the file. The second program will read the list of this serialized tree nodes, and need to be able to reconstruct this list of strings to a list of C++ objects (and later from this list I can reconstruct the tree).

I think the LLVM framework may have something to offer here. Can someone give me some pointers on this? Not necessary a full answer, just somewhere for me to start.

Upvotes: 0

Views: 124

Answers (1)

arrowd
arrowd

Reputation: 34391

You can compile your generated code with clang and emit LLVM bitcode (-emit-llvm flag). Then, statically link your program with parts of LLVM that read bitcode files and JITs them. Finally, take compiled bitcode and run JIT on them, so they will be available in your program's address space.

Upvotes: 1

Related Questions