This question already has answers here:
How can I convert string to code at run time
(4 answers)
Closed 9 years ago.
Is it possible to convert a raw string to code in c++?
For example I have a string
string s = "cout << "Hello World";";
I want to generate that code programatically. Maybe i want to insert that code in various parts of the program dynamically.
cout << "Hello World";
Also, is it possible to generate code using loops in c++ maybe using pre-processor directives?
It looks like you want something akin to the eval function provided by Lisp, Python, perl, and many other languages.
There is no such capability in C++. It just doesn't exist, by design.
One way to get around this missing functionality is to make your program write a program, store it in a file, invoke the compiler, and invoke the executable generated by the compiler. That's rather ugly. Anything you do is going to be rather ugly.
Is it possible to convert a raw string to code in c++?
C++ is typically a compiled language. This makes what you're trying to do tricky. In order to achieve what you're saying, you'd need to either have the code interpreted at runtime (in which case you'd be better served by binding to a scripting language such as Python or Lua), or embed or call a C++ compiler and pass the code to that, then run it.
It is possible that this is a XY problem and that the solution you are looking at is overly complicated for the actual root problem you are trying to solve. It may be an idea to put up a description of why you're trying to do this, as there may be a much simpler way to achieve the end result you want.
Related
This question already has answers here:
Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?
(16 answers)
Is there a C++ decompiler? [closed]
(5 answers)
Closed 4 years ago.
I lost the source code to an executable file but still have the actual file. Is there any way to retrieve the original C++ code?
Duplicate of this question here.
Yes, it is possible, however when it comes to peeking function bodies and the like, you might have a little less luck. Operating systems like Kali Linux specialize in de-compilation and reverse engineering, so maybe look into a VM of that. And of course, windows has a lot of applications you can use as well to check the application code.
Look over the other question for specific app suggestions. :)
Edit : You will most likely have lost all your logic and function bodies, but you might be able to recover the overall structure. It's your EXE so you might be more familiar with how it was all connected up.
You cannot get the original source code but you can decompile the binary into source code using tools given in this similar question: Is there a C++ decompiler?
The output source code will not look like the original as the compiler will have optimised the original source when generating the executable.
Short answer NO.
Long answer, because C++ doesn't use some intermediate code like C# or Java you cannot decompile the app in some readable format. But if you can read assembly maybe you can save some time.
This question already has answers here:
Is it possible to create a function dynamically, during runtime in C++?
(14 answers)
Closed 8 years ago.
In C++, I have to make some user-defined actions on each cells of a big table.
Because of the size of the table, I'd like not to use interpreted instructions but to compile during runtime a function that I will call on each cell.
The user-defined actions are pretty simple :
if ((state1 && state2) || state3) then change_a_value_in_memory
That's why I don't need to use the LLVM or other JIT libraries.
I hesitate to just use mmap and add the code in hex directly.
I'd like to know if it exists better solutions, or, if not, where I can find the basic format of a C++ function code to directly write it in memory.
Thanks, and sorry for my english :/
This is not the most elegant, but it works always: generate a file with the C++ code of your function, call the compiler using system(), load the generated .so file using dlopen, and use the function!
This will take some time (due to the compiler call), but if you keep the function and maintain a database of the functions you already have, then you can save the amount of compilations.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Both Convert string to variable name or variable type and How to use a string as a variable name in C++? answers say you can not use a string as a variable after compile time. However, they mention that higher level languages such as python can. As I understand it, Python is written in C from this https://softwareengineering.stackexchange.com/questions/20988/why-is-python-written-in-c-and-not-in-c .
So if python is written in C, and it can use string as variable, then why cant people do this in C++.
I guess the question is not clear. From the analogies in comments,
If Python is made from C, I would assume there is some function written that allows Python to be dynamic. So why cant that functionality be written without all of the other parts of Python.
The CPython implementation - the implementation of Python written in C - uses the C language to implement a certain kind of variable lookup that makes Python behave like Python and not like, say, C or BASIC.
So, you can certainly use C or C++ to implement string-named variable lookup. Just don't expect the compiler to recognize it, because it's not part of the C/C++ language. The end product - the compiled executable - will support the concept, though.
For example, in C++, using Boost:
std::map<std::string, boost::variant<std::string, int>> _;
_["name"] = "user";
_["index"] = 1938107;
std::cout << _["name"] << _["index"] << std::endl;
Output:
user1938107
You can also make it interoperate with regular variables known to the compiler, if but there are no off-the-shelf classes to help you there.
When a C++ program is compiled, the variables names aren't put into the resulting executable. Once the compiler has everything figured out, they are literally discarded. All that is left behind are the very low level pieces of assembly language instructions and memory addresses. So the language is fundamentally engineered in a way that doesn't allow for what you want.
Some other languages, like Python, preserve the name information. They don't compile in the same way as C++. There's usually a lot more interpreting at runtime happening. At some fundamental level, the variables in a Python program probably end up in some kind of underlying data structure - perhaps a map of names to values. That way the language can support on-the-fly lookups and such of variable names.
So at best in C++, you can engineer your own data structures or framework in a similar manner - to hold data with an associated name and then be able to query by name to retrieve the relevant data. (Or of course, you could search for someone else who has already implemented such a thing.)
A screwdriver can't drill a hole. But you can use a screwdriver to build a drill.
In another way, I think you CAN create some TYPE of variables from string or something using some trick, like in the Factory Design Pattern, but, that's not a language feature, you will need to register the type's name and the type's creator function first.
std::map<string, creating_function> lookup_table;
lookup_table["class_1"] = &class_1_creator; // register type and creator
obj_instance& Create(string type_name, parameters_passed_to_the_creator) // create a variable
{
return lookup_table[type_name](parameters_passed_to_the_creator);
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
compile and run c++ code runtime
I want to take as an input an expression from the user as a string and compile it into a callable c++ function. Are there any tools that allow you to do this easily?
Basically, How do I compile an Expression Tree into a callable method, C#? seems similar to what I want to do except that I need to do this in c++ and not c#.
I can certainly make a sort of generic evaluator using lex and yacc but I don't want to have to parse the string every time. Basically this expression will run in a critical inner loop so I'm looking for a way to "compile" it at run-time.
It's not easy... If you want my two cents, I will follow these steps:
Create an interface for the code that you must create at runtime. At first, you create an interface for what you can do. For example your class must inherit from a pure virtual base class that will represent your interface. Take care that your program will use not arbitrary code, but code created in a specific way, because it must know how to use it.
Call the compiler from inside your program. The compiler should create a library from your source code. You can use a predefined project that you store somewhere, and then replace its source file with your own. So it can be easy to obtain a right library.
Put your library in a specified source where you can find it.
Load the library at runtime. If you search, you will see that it's possible to load dynamic libraries at runtime, not only at linking time (in this way, for example, you can create plugins for programs). So your program can load your library and use it. For example you can find some information here.
But, as others have said, it's not a trivial task.
EDIT: Another solution is to check a parser like boost::spirit::qi, that is well used can give extremly helpful results.
You have to parse the expression to an abstract syntax tree and walk it or evaluate it in-place. Something like this should satisfy your needs for a simple mathematical expression.
You can write your mini-interpreter. With the commands same with c++ (not all of them). Of course your compiler will optimize it but not sure how much. I did it for assembly in qbasic (mov, add, sub...) but it was quite slow because of being an interpreter of an interpreter :D
Did you think about Evolutionary computation and fitness functions? Worth looking at.
You can create a data structure that represents your parsed expression tree, and the overhead of evaluating that at runtime will be small compared to parsing the string every time.
Actually getting a callable method in C++ will be quite difficult, in that you would have to generate object code and dynamically load it into your program. This would duplicate a lot of what the whole compiler tool-chain does.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Have you used any of the C++ interpreters (not compilers)?
Hi,
I am currently learning C++ and a beginner in programming in general. I've been trying to write some code to a few programming problems from the book I'm using. What I find is that often I make mistakes in what I write and those mistakes come up when the program is run. Its usually quite obvious where in the program I've gone wrong when there is regular output. But in a long computation I'm often not sure why a particular code has acted a certain way. I've also looked at Python recently. Python works with an interpreter, which can take any piece of Python code and compute its output.
I was wondering if there was something similar for C++. Right now when I want to check a line or block of code I have to comment out a lot, save it, compile it, and then run it from a command line. And I have to do that many times for a single error until I've solved it. Is there a way to type code into an active terminal which would run code and show me output? What would be better still would be a way to select a block of code (like you select text) or multiple blocks (to see how a function is being handled) within the IDE and click run to run just that block of code and see its output without having comment out irrelevant lines or to save the file. The compiled code could just reside in memory.
CINT is a c & C++ interpretter that accepts nearly all valid C++. Unfortunately many Linux distros do not offer it, and you'll probably have to build it from source... and that is a non-trivial task.
Typically a debugger is used to step through code line by line, starting at a chosen breakpoint, and keep watch of all variables/values.
Unit testing is a technique to test smaller pieces of code.
A stepping debugger, as found in most IDEs will help you with this.
Here (for example) is a description of how to set the Execution point in In Visual Studio, which sounds like what you want to do.
For certain situations, the "Immediate Window" may be of use to you. It allows you to type in expressions to evaluate immediately.
Rather than just running individual lines independently, or relying on print statements to tell you the state of whatever variables you have decided to print, you can use the debugger to run to the point of interest (where you will have set a breakpoint), then you can examine the state of any in-scope variables, or even alter the normal flow of the program.
There are some solutions that try to do this - the ones I know are Ch and TextTransformer.
However, I doubt that this works very well. C++ is not at all designed to run as an interpreted language.
One of the problems is that C++ is very, very hard to parse. And this makes it very hard to provide certain types of tools that are usual for other languages. For example, I don't think there is any C++ refactoring tool that really works well.
C++ is a compiled language not like python. But there are few c/c++ interpreters out there but not sure about their features. Check these out: Ch interpreter and CINT
If you really want to learn c++ please do not use the c/c++ interpreters.
If you insist on using a interactive interpreter there is since a long time CINT which is the default interpreter used in the ROOT project. It got better over the years, but still has only limited capabilities when dealing with templates. Also, there is a move to replace it with a JIT compiling interpreter based on clang inside the ROOT project.
If I were you I would learn how to run compiler and an interactive debugger like suggested in some comments already.