user3340001
user3340001

Reputation: 237

Is there any way to transform strings into compileable/runnable code?

For example, suppose we have a string like:

string x = "for(int i = 0; i < 10; i++){cout << \"Hello World!\n\";}"

What is the simplest way to complete the following function definition:

void do_code(string x); /* given x that's valid c++ code, executes that code  as if it were written inside of the function body */

Upvotes: 3

Views: 168

Answers (4)

ceilingcat
ceilingcat

Reputation: 781

Use the Dynamic Linking Loader (POSIX only)

This has been tested in Linux and OSX.

#include<fstream>
#include<string>
#include<cstdlib>
#include<dlfcn.h>

void do_code( std::string x ) {
  { std::ofstream s("temp.cc");
    s << "#include<iostream>\nextern \"C\" void f(){" << x << '}'; }
  std::system( "g++ temp.cc -shared -fPIC -otemp.o" );
  auto h = dlopen( "./temp.o", RTLD_LAZY );
  reinterpret_cast< void(*)() >( dlsym( h, "f" ) )();
  dlclose( h );
}

int main() {
  std::string x = "for(int i = 0; i < 10; i++){std::cout << \"Hello World!\\n\";}";
  do_code( x );
}

Try it online! You'll need to compile with the -ldl parameter to link libdl.a. Don't copy-paste this into production code as this has no error checking.

Upvotes: 1

waTeim
waTeim

Reputation: 9225

Not directly as you're asking for C++ to be simultaneously compiled and interpreted.

But there is LLVM, which is a compiler framework and API. That would allow you to take in this case a string containing valid C++, invoke the LLVM infrastructure and then afterwards use a LLVM-based just in time compiler as described at length here. Keep in mind you must also support the C++ library. You should also have some mechanism to map variables into your interpreted C++ and take data back out.

A big but worthy undertaking, seems like someone might have done something like this already, and maybe Cling is just that.

Upvotes: 3

M.M
M.M

Reputation: 141554

Works for me:

system("echo \"#include <iostream> \nint main() { for(int i = 0; i < 10; i++){std::cout << i << std::endl;} }\" >temp.cc; g++ -o temp temp.cc && ./temp");

Upvotes: 0

Holstebroe
Holstebroe

Reputation: 5133

The standard C++ libraries do not contain a C++ parser/compiler. This means that your only choice is to either find and link a C++ compiler library or to simply output your string as a file and launch the C++ compiler with a system call.

The first thing, linking to a C++ compiler, would actually be quite doable in something like Visual Studio for example, that does indeed have DLL libraries for compiling C++ and spitting out a new DLL that you could link at runtime.

The second thing, is pretty much what any IDE does. It saves your text-editor stuff into a C++ file, compile it by system-executing the compiler and run the output.

That said, there are many languages with build-in interpreter that would be more suitable for runtime code interpretation.

Upvotes: 4

Related Questions