How to run C ++ code from C ++?

If I have C ++ code as the number of lines (data) in a C ++ program, can I execute the contents of this line?

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

+1
source share
5 answers

Short answer: you cannot.

The answer is slightly long: C ++ has no reflection and is usually compiled, so there is no support of this kind, and it is not easy to add.

Work around:

  • Use the built-in dynamic language, for example [python | tcl | ruby | ...], combined with your C ++ code. Now you need to have a dynamic language (not C ++) in the data.
  • Use a C ++ interpreter like cint or ch. This connects you to the interpreter.
  • Use the C ++ system compiler to create a dynamic library from your code and link to it on the fly. Risky and systemic.
  • Use a different language.
+10
source

Not. Since C ++ is a static language, you cannot dynamically define arbitrary code.

You could interpret it or even compile and run it separately, as Kate suggested

+5
source

if you want to compile C ++ code on the fly and run it? of course if you have a compiler for you

+3
source

Not one of the main implementations of C ++ has this function, since C ++ does not reflect.

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

http://www.softintegration.com/

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

You can embed the Ch interpreter in your C ++ application and run dynamic C ++ code in it.

+2
source

C ++ cannot do this - the compiled program does not know the syntax of the source language, identifier names, etc.

Even if you try to write a string to a file by calling the C ++ compiler to create a dynamic library and load and call, this call will not have any information about your program - it will not be able to refer to your variables, etc.

The most common reason to do this is to be able to evaluate expressions from strings. Writing code for this from scratch is definitely nontrivial, but depending on your specific requirements, you should find a library or an embedded scripting language to do something you need.

After a quick google, I found this - rather C than C ++, and I don't know how good it is. This is written as a demo of a parser generator that I have not heard of. You can find alternatives in the form of demos of more well-known parser generators such as yacc, bison, yacC ++ or antlr.

+2
source

Source: https://habr.com/ru/post/1305989/


All Articles