开发者

How to run c++ code from c++?

开发者 https://www.devze.com 2022-12-08 16:24 出处:网络
If I have some c++ code as a string quantity (data) in a c++ program开发者_如何学JAVA, can I execute the contents of that string?

If I have some c++ code as a string quantity (data) in a c++ program开发者_如何学JAVA, can I execute the contents of that string?

As using the CodeDOM in C# or the eval function present in perl, python, etc..


Short answer: you can't.

Slightly longer answer: c++ has no reflection, and is generally compiled, so there so is no support for this kind of thing, and it can not be easily added..

Work arounds:

  1. Use an embeddable dynamic language like [python|tcl|ruby|...] in concert with your c++ code. Now you need to have the dynamic language (rather then c++) in the data.
  2. Use a c++ interpreter like cint or ch. This binds you to the interpreter.
  3. Use the system c++ compiler to construct a dynamic library from your code and link to it on the fly. Risky and system dependent.
  4. Use a different language.


No. As C++ is a static language, you can not dynamically eval arbitrary code.

You could interpret it or even compile and run it seperately as Keith suggested


if you mean compile C++ code on the fly and run it? sure if you have a compiler available to you


Non of the mainstream C++ implementations have that feature, as C++ is not reflective.

However, take a look at Ch, it might be what you are looking for:

http://www.softintegration.com/

http://en.wikipedia.org/wiki/Ch_interpreter

You can embed Ch interpreter into your C++ application and run dynamic C++ code inside it.


C++ cannot do this - the compiled program has no knowledge of the source language syntax, identifier names etc.

Even if you go to the effort of writing the string out to a file, calling a c++ compiler to generate a dynamic library and loading and calling it, that call won't have any knowledge of your program - it won't be able to reference your variables etc.

The most common reason to want to do this is to be able to evaluate expressions from within strings. Writing the code to do this from scratch is definitely non-trivial, but depending on your specific requirements, you should be able to find a library or embeddable scripting language to do roughly what you need.

After a quick Google, I found this - C rather than C++, and I don't know how good it is. It's written as a demo of a parser generator that I haven't heard of. You might find alternatives as demos of better known parser generators such as yacc, bison, yacc++ or antlr.

0

精彩评论

暂无评论...
验证码 换一张
取 消