execute C++ from String variable

Directly, no. But you can:

  • write that string to a file.
  • invoke the compiler and compile that file.
  • execute the resulting binary.

No, C++ is a static typed, compiled to native binary language.

Although you could use LLVM JIT compilation, compile and link without interrupting the runtime. Should be doable, but it is just not in the domain of C++.

If you want a scripting engine under C++, you could use for example JS - it is by far the fastest dynamic solution out there. Lua, Python, Ruby are OK as well, but typically slower, which may not be a terrible thing considering you are just using it for scripting.

For example, in Qt you can do something like:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QScriptEngine engine;
    QScriptValue value = engine.evaluate("var a = 20; var b = 30; a + b");

    cout << value.toNumber();

    return a.exec();
}

And you will get 50 ;)


You will need to invoke a compiler to compile the code. In addition, you will need to generate some code to wrap the string in a function declaration. Finally, you'll then somehow need to load the compiled code.

If I were doing this (which I would not) I would:

  1. Concatenate a standard wrapper function header around the code
  2. Invoke a compiler via the command line (system()) to build a shared library (.dll on windows or .so on linux)
  3. Load the shared library and map the function
  4. Invoke the function

This is really not the way you want to write C code in most cases.


C++ is a compiled language. You compile C++ source into machine code, the executable. That is loaded and executed. The compiler knows about C++ (and has all the library headers available). The executable doesn't, and that is why it cannot turn a string into executable code. You can, indeed, execute the contents of a string if it happens to contain machine code instructions, but that is generally a very bad idea...

That doesn't mean that it wouldn't be possible to do this kind of run-time compilation. Very little (if, indeed, anything) is impossible in C++. But what you'd be doing would be implementing a C++ compiler object... look at other compiler projects before deciding you really want this.

Interpreted languages can do this with ease - they merely have to pass the string to the interpreter that is already running the program. They pay for this kind of flexibility in other regards.

Tags:

C++