Question:
Is there a way I can use the python "exec" thing, but in C++?
magicaxis
2010-07-26 01:24:36 UTC
Is there an equivalent keyword or function, or is there one in a library I can use?
Three answers:
Cubbi
2010-07-26 06:27:40 UTC
No. That's one of the main distinctions between interpreted and compiled languages. To execute a line such as "return 0;", you would have to execute the C++ compiler to convert it to object code, execute the linker to turn it into a dynamic library, load the library, and then pass control to it.



While it's hardly a good idea to distribute your program with a compiler/linker (or require their presence to run it), a viable way to do this is to distribute your program with a C++ interpreter, such as http://en.wikipedia.org/wiki/Ch_interpreter (although that one is mostly C). Then you would be able to pass your "return 0;" to that interpreter, and get the result immediately.



Oh, there's another C++ interpreter around, CINT: http://root.cern.ch/drupal/content/cint

it seems to be more robust.
2010-07-26 18:16:03 UTC
Well, based on your example, and from what I read from the python manual, it looks like you're looking for macro functionality.

In C/C++ we have the #define instruction which substitues text for other text or a numerical value.



Everytime the 'number' text is encountered in the C/C++ source file, it is replace with 1 when the program is compiled:

#define number 1

cout << number; // print out 1



Everytime the 'foo' text is encountered in the source file, it is replaced with the text "fuzz"

#define foo "fuzz"

cout << foo; // prints out fuzz



I don't know if the functionality is still present (I haven't used this in many years), but you can also have a macro accept a parameter like this:

#define trythis(p) cout << p

So, when the compiler encounters this in the source file::

trythis(4);

It gets translated to this:

cout << 4; // print out 4



The #define instruction doesn't really support multi-line macros. You have to use semicolons:

#define moo int myint;char mychar;cout << "hello"



moo;

Translates to:

int myint;char mychar;cout << "hello";



As far as execution goes, well, you don't need something like exec.

If I have code like this:

#define moo cout << "boo\n";

cout << "Hello\n";

moo

cout << "foo\n";



The compiler replaces 'moo' with 'cout << "boo\n";' during compilation.

So, it would be as if I wrote:

cout << "Hello\n";

cout << "boo\n";

cout << "foo\n";



output:

Hello

boo

foo
?
2010-07-26 08:46:07 UTC
as in execute a command? (I don't do python)

either system() or if on a unix box there is fork & exec execl exec execve (use man exec* for more info)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...