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

前端 未结 5 1593
夕颜
夕颜 2021-01-24 02:03

If I have some c++ code as a string quantity (data) in a c++ program, can I execute the contents of that string?

As using the CodeDOM in C# or the eval function present

相关标签:
5条回答
  • 2021-01-24 02:14

    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.
    0 讨论(0)
  • 2021-01-24 02:14

    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.

    0 讨论(0)
  • 2021-01-24 02:28

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

    0 讨论(0)
  • 2021-01-24 02:34

    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

    0 讨论(0)
  • 2021-01-24 02:38

    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 讨论(0)
提交回复
热议问题