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

前端 未结 5 1653
夕颜
夕颜 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: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.

提交回复
热议问题