So basically what I need isn't a specific code (of course that would be great), but just an idea and methods on how to achieve my goal.
1) I have to create a program in C++ , which generates a little example of C++ code, that is each time a bit different. (This causes no problems for me, I will use a template and randomize some variables in the code, which will make it unique every time.)
2) I will display the generated code and the user will have to type in, what he thinks the code prints out.
And here is where the problems start:
3) I have to take the generated code and compile it somehow to get a string with the text that the program would have printed out.
4) And then compare the string with what the user has typed in.
So the step 3) is where I stop and can't figure it out without help... I was thinking to write the generated code in a function of a .cpp file and then call that function, but I couldn't get it to work, so I started to think, I should ask an expert, maybe there are some other methods or ideas how to achieve this.
You can invoke the c++ compiler just like you'd invoke any external tool. E.g.
system("g++ test.cpp")
or use popen or whatever else is offered by your platform.You could also look into integrating a library that implements a compiler into your program. For that you might want to look into clang and llvm.
I have not used this but it is free and also does not compile but interpret. Very suitable for your problem, worth a shot...
http://root.cern.ch/drupal/content/cint
It's probably simplest to wrap 2/3/4 into a script, and invoke that with
system
orpopen
. The script can make sure the filenames are unique, fold stderr into stdout, etc. etc.Your running program isn't really interacting with the compiled code, just reading the output, so keeping it as a seperate process is probably easiest. The script can add some markup to help you distinguish compiler output/errors from the program output.
I haven't written a batch file for years, but once you know how to run your compiler from the command line (ref), you can write a script to:
.cpp
file.exe
then, in C++ you just need to save the code to the
.cpp
file the script expects, execute the script likesystem("myScript.bat")
, and then read the output file.If you don't want to write a seperate batch script, you can just call
system
once to invoke the compiler, and again to execute the resulting.exe
.I think you are looking for a way to script c++. Have a look at http://www.softintegration.com/ or this stackoverflow question Any tutorial for embedding Clang as script interpreter into C++ Code?.
Would something like Geordi work?
why dont you compile the generated code standalone using system() call? system("g++ temp.cpp -o temp.exe); --something of this sort and then based on the return value you can run temp.exe again like system("temp.exe"); Ofcourse you can print the output from temp.exe to a file and read that file to get the output of temp.exe to your current program..