Creating a .cpp, compiling and executing

Hello people,

I'm trying to create a program that dynamically creates strings of code, and as C/C++ is a compiled system, it's not possible to use something like eval() (from JavaScript). So, I thought I could create another .cpp file, compile it, and then execute the .exe. Can someone help me with this?
Last edited on
Maybe you need to use system calls. And then you have to consider the problems of portability.
Or , maybe you could include the compiler libraries in your code...but again portability issues.
But witch libraries I should use to do this? I've never used C/C++ to execute a .exe file, neither to compile another .cpp. I'll need an example or, at least, the function calls and library names.
It sounds terribly risky and error-prone. If you give more details I can probably come up with something. What kind of input will the program take and what should its output be?
I'm trying to develop a program that can receive via keyboard new strings of code and execute them. E.g.:

The main program "Main" reads the string from keyboard:
printf("Hello.");
Then, it shows as output:
Hello.

If C/C++ wasn't a compiled system, it would be something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdlib.h>
#include <iostream>

using namespace std;

#define CODE(code) code

main()
{
   string code;
   
   cin >> code;
   
   CODE(code);
   
   cout << endl << "Press ENTER to exit." << endl;
   cin.ignore();
   cin.ignore(1, '\n' );
}


Then, as it wouldn't work this way, I thought about creating another .cpp file, compile and execute it. It's just a general view of the idea but i think you can get it.

Ah, and the input could be any kind of code in C/C++, like a for, if, scanf, etc.
Last edited on
It probably isn't worth your time to roll your own private interpreter. I suggest you simply embed a pre-made interpreter.

Tcl
http://wiki.tcl.tk/

Python
http://www.python.org/

Scheme
http://www.plt-scheme.org/

You also have to deal with sandbox issues. All of the above are very good at that.

Hope this helps.
Thanks guys. I'd really like to make it in C/C++ but I'll wait some years maybe. XD
try bison

http://www.gnu.org/software/bison/

You could probably copy the c grammar almost directly.
Last edited on
Topic archived. No new replies allowed.