I have found a need to execute C++ code in the terminal. When giving thought on how to do this, Python's exec
command is perfect. Sadly, I cannot use this as I need a C++ parallel.
Is there a similar command in C++?
I have found a need to execute C++ code in the terminal. When giving thought on how to do this, Python's exec
command is perfect. Sadly, I cannot use this as I need a C++ parallel.
Is there a similar command in C++?
There is no perfect equivalent of exec()
in C++ that I'm aware, as C++ isn't designed to be used this way normally.
system()
comes to mind as a near equivalent off the top of my head, although I will warn you that system()
is not usually recommended for use in production code.
However, if none of the reasons in the linked question bother you, you could theoretically construct an exec()
from a combination of system()
and exit()
:
void exec(const char* command, int code=0) {
system(command);
exit(code);
}
Edit: I may be way off. There may be an exec in C++. Also, see this question.
The short answer is no, c++ doesn't have support for evaluating and executing arbitrary code.
If you need scripting support user a scripting language. Lua and python are reasonably easy to integrate. chaiscript even looks a lot like c++ code.
You could invoke a compiler from within your program and then run the resulting executable but i doubt that's a good solution to whatever your problem is.
https://docs.python.org/3/library/functions.html#exec
exec(object[, globals[, locals]])
This function supports dynamic execution of Python code.
There is no equivalent or similar function in C++.