Dynamic recompiling
Angeljruiz (167)
Nov 16, 2012 at 6:53am UTC
Hey everybody,
Well i created my first emulator. Currently, it only interprets. Ive learned first hand the obvious - its slow. So my solution is to make it dynamically recompile the code. Problem is i dont know where to start with dynamic recompiling. If anyone could give some extremely basic code examples of a link it would be great. Thanks :D
Jan Pasierb (16)
Nov 16, 2012 at 10:49am UTC
Dynamic compilation in C++? Good luck.
Seriously though try java's JIT mechanism.
JLBorges (1336)
Nov 16, 2012 at 2:28pm UTC
A pure interpreted language would be the most appropriate to implement read-eval-print loops.
http://docs.python.org/2/library/code.html
And then hook C++ up with a glue library - for instance, Boost.Python.
http://www.boost.org/doc/libs/1_52_0/libs/python/doc/index.html
> Problem is i dont know where to start with dynamic recompiling.
> If anyone could give some extremely basic code examples of a link it would be great.
Here is a toy example of dynamic recompiling with C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
int f( int x, int y )
{
return
x+y-45;
}
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
std::vector<std::string> read_lines( const char * path2file )
{
std::vector<std::string> vec ;
std::ifstream file(path2file) ;
std::string line ;
while ( std::getline(file,line) ) vec.push_back(line) ;
return vec ;
}
void write_lines( std::vector<std::string>& lines, const char * path2file )
{
// make a backup copy of the file first
std::ofstream file(path2file) ;
for ( const auto & s : lines ) file << s << '\n' ;
}
std::string get_fn_expr()
{
std::string expr ;
std::cout << "enter expression for f(x,y):\n\tfor example x*x*x + y*y - 23 ? " ;
std::getline( std::cin, expr ) ;
// validate expr
return expr.empty() ? get_fn_expr() : expr ;
}
void do_recompile_and_run()
{
std::cout << "recompiling. please wait..." ;
// adjust command(s) appropriately for the implementation
std::string recompile_cmd = "/bin/g++ -Wall -std=c++11 --pedantic -Wall -Wextra -Werror " ;
recompile_cmd += __FILE__ ;
recompile_cmd += "&& ./a.out run" ;
std::system( recompile_cmd.c_str() ) ;
}
void modify_function_and_recompile()
{
std::vector<std::string> code = read_lines(__FILE__) ;
enum { LINE_TO_MODIFY = 3 } ;
code[LINE_TO_MODIFY] = " " + get_fn_expr() + ';' ;
write_lines( code, __FILE__ ) ;
do_recompile_and_run() ;
}
void run()
{
std::cout << " done. running the program now.\n" ;
int x, y ;
std::cout << "x? " && std::cin >> x ;
std::cout << "y? " && std::cin >> y ;
std::cout << "f(x,y) evaluates to " << f(x,y) << '\n' ;
}
int main( int argc, char *[] )
{
if ( argc == 1 ) modify_function_and_recompile() ;
else run() ;
}