c++ version of python's exec() functions

179 Views Asked by At

objective: executing a string of c(++) code with some kind of function comparable to the exec() function in python.

example in python:

exec('print("hello world")')
#out:
#hello world

question:

is there a c++ version of exec in python?

3

There are 3 best solutions below

1
On BEST ANSWER

Well, technicall, you (maybe) can. But it's hardly a justifiable effort, there are other scripting languages that can be integrated in C++. For example Lua. Just to think about it, the following could work, if you have a method int excuteCode(std::string code)

  1. Copy that string into a template that wraps it in some function. The following is an idea of such a template:
int userFunc()
{
    %code%
}
  1. Write the template to a file
  2. Build a dynamic library (e.g. a .dll on windows) from that file (call compiler and linker via system or OS-specific methods)
  3. Load the dynamic library into your running program (again, OS-specific methods)
  4. Load the required method userFunc and execute it.
0
On
#include <iostream>
int main(void) {
    system("python -c \"print('hello world')\"");
    return 0;
}

For system commands...?

0
On

but, is there a c++ version of exec in python?

you wan to execute C language statements from a string! so that is not possible with c.

why

because c is compiled language, the program first compiled and then executed. its possible in python as its interpreted language,means program is compiled by just-in-time compiler at runtime. hope this will help.