Parsing a string as a line of code in C ++

Is it possible that a string variable can be parsed as an actual line of code in C ++? For example, can this string be "x=0"

parsed as valid code and set the value x

(some random variable in the program) to zero? What I plan to do with this is what I want to make a simple C ++ plotter. The user enters a function (the function will be in terms of x

and y

and will have a value of 0) to be constructed as a string (for example 2*y+x

), which will then be converted to a code object and then accordingly using a loop.

+3


source to share


3 answers


Since C ++ is a compiled and linked language, it is not suitable for on-the-fly evaluation.

But in the past I've achieved something similar to your goals with C ++ embedding a Python interpreter to evaluate Python code as strings on the fly and pipe the results to C ++ code.

Some other popular scripting languages ​​that can be embedded into a C ++ program are Lua and Squirrel .



In Java, I did the same by introducing the Groovy interpreter .

You need to integrate the scripting interpreter into your code by nesting it, and then pass the values ​​from the scripting language code to your C ++ code using the sorting process .

If you really want C ++ syntax that can be interpreted, it is theoretically possible to develop a dynamic parser and interpreter for a subset of the language, but C ++ is a complex language, and such a task would be a huge task fraught with difficulties and mostly a use case for the wrong tool for work.

+1


source


The short answer is no. You cannot compile C / C ++ on the fly like this, as it is a compiled language, not an interpreted one.



But here's the idea: you can inline a JavaScript interpreter using the SpiderMonkey API , which can interpret all of your example code snippets, as JavaScript syntax is very similar to C / C ++ in that respect.

0


source


The short answer is yes. Compiling C ++ on the fly works fine using C ++ JIT. From llvm.org

A Just-In-Time (JIT) code generation system that currently supports X86, X86-64, ARM, AArch64, Mips, SystemZ, PowerPC, and PowerPC-64.

It assumes that you are willing to link most of the compiler in your program to achieve this. With a concerted effort, you should be able to write "eval" on top of your existing API.

0


source







All Articles