I realize that this (Is it possible to dynamically compile and execute C# code fragments?) is a similar question, But it is 5 years old, and also in C#. Basically what I would like to do is have a program take code from a text file, and then compile and run it. If C++ is not a good language for this a recommendation would be helpful. Here is my basic goal.
Have code that runs code from a text file(ex; Test0).
Have the code from the file output 'Hello'
Then make another file(Test1) and change the output to a mixing of those letters
When it saves, it overwrites any previous file of the same name
The Code from the text file then ends.
The original program then makes Test0=Test1
The program then loops or ends.
Sorry about the coloring, the only way I know how to make the enter key strokes to appear is the code exert thingy.
The most basic solution is to invoke the C/C++ compiler to compile the text file each time it changes and before you call it. But what you are probably looking for is an interpreter, not a compiler. There are various C/C++ interpreters (which you can search for) that may meet your needs. However, C/C++ is not traditionally interpreted. More popular interpreted languages are Python, Lua, and JavaScript. With those, it is possible to embed the source code of the interpreter into your C/C++ program and interact with it --- it is possible to call the interpreted language's functions from C/C++ and vice-versa.
Related
I need to define functions in c++ code to be user defined. Basically that he writes the function in form of a string which is exact c++ code, then use that function in the very next line of code.
I have tried to append output to a file which is imported, but it obviously failed
You simply cannot do it. C++ code can not be interpreted at run-time. You may want to try Qt/QML which will give an opportunity to run a javascript code or an entire QML file from network/string or any other method which can deliver your code to the host application.
I assume you are talking about a pure function such as a mathematical formula.
To my knowledge, what you ask is not possible without
a) writing your own parser, that effectively creates functions from strings or
b) using external libraries - a quick google search brought be to this library that seems to provide the functionality you are looking for. I have no personal experience with it, though.
As #Useless pointed out, "editing" the code after compilation is not intended in a compiled language as c++. This could be tricked by having a second code compiled and executed in the background; this, however, seems rather unelegant and would rely on additional threads, compilers and the operating system.
Python and R overs a friendly way for one to understand the source code written in these languages and users can stop at a given point and inspect the objects (as objects in these languages can be printed in a user friendly way while debugging).
For C++, I don't know if there is similar way. I currently don't use IDE. I know the C++ source code can be compiled with the -g option to allow the use of gdb. But this is still much more difficult than what is in python and R. Does anybody know what might be the best to step through C++ source code and inspect objects when necessary (for code understanding purpose)? Thanks.
Because Python is an interpreted language, you can have this friendly "debugging experience". C++ is a compiled language so when the executable is running, the run-time knows nothing about the source code. That is why we have to use a GDB or something that can help us to associate the binary and the source code.
So I think you have to get familiar with GDB or just pick a nice IDE.
Eclipse is quite good! You can do anything with it because there are so many plugins for it.
I am using C++ (in xcode and code::blocks), I don't know much.
I want to make something compilable during runtime.
for eg:
char prog []={"cout<<"helloworld " ;}
It should compile the contents of prog.
I read a bit about quines , but it didn't help me .
It's sort of possible, but not portably, and not simply.
Basically, you have to write the code out to a file, then
compile it to a dll (invoking the compiler with system), and
then load the dll. The first is simple, the last isn't too
difficult (but will require implementation specific code), but
the middle step can be challenging: obviously, it only works if
the compiler is installed on the system, but you have to find
where it is installed, verify that it is the same version (or
at least a version which generates binary compatible code),
invoke it with the same options that were used when your code
was compiled, and process any errors.
C++ wasn't designed for this. (Compiled languages generally
aren't.)
The short answer is "no, you can't do that". C and C++ were never designed to do this.
That's pretty much also the long answer to the actual question, but I'll expand a bit on a few ideas.
The code, as compiled by the compiler is pretty certainly not trivial to add things to. There are a few techniques that can be used to "add more code" to a program:
Add a dynamic shared library (DLL), which contains code that has been compiled separately to the existing code. You could of course also have code in your program to output some code, compile this code with the compiler, link it into a dynamic library, and load it in your code.
You could build your own little code-generator that generates machine code in a chunk of memory. Note that you probably need to call a "special" memory allocation function, as "normal" memory allocations are typically not allowed to be executed - you need to allocate "with execute permission" - VirtualAlloc in Windows does have such a flag, and mmap in Linux/Unix flavours does too. And of course, you pretty much have to "be a compiler" to achieve this.
You could naturally also invent your own interpreted language, which would allow your program to load in for example a text-file with commands/instructions to be executed, or contain text inside the program for execution with this language.
But like I said to start with, this is not what C and C++ (and most other compiled languages) were meant for, so it's not going to be as simple as "stick some C++ code in a string, and make it run".
It depends why you want to do this.
If it's for efficiency reasons - you know what a function does only at run time, but it has to be very efficient - then what was already suggested (writing to a file, compiling to a dll / so and dynamically loading it) is your best option.
BUT if the reason you want this is to allow for user-input behaviour, say a general function your read from a database (behaviour or a unit ingame? value of a field in a plot?) - or more generally you just want to change / augment behaviour at runtime with little concern for efficiency, I recommend using an outside scripting language like lua, which easily interacts with your compiled C++ code.
The C and C++ languages compile to binary machine code, unlike Java and C# which generate instructions for a 'virtual machine' or interpreted scripting languages such as JavaScript. The compilation of C++ is performed by a separate executable, the compiler, which is not incorporated into the resulting executable.
So the language does not have any built in "eval" capability to translate further code once compilation is finished.
It's not uncommon for new C/C++ programmers to think they need to do this, but they typically don't. Perhaps you could expand further on what you're actually looking to do.
But if you do actually need to be able to do this, your options are:
Write code to compile a new executable with the new code and then run the resulting program.
Write a simple parser and "virtual machine" of your own,
Look at incorporating an embedded scripting/interpreted language such as Lua,
Try and wrap your head around integrating CINT,
See also: Scripting language for C++
This may be kind of basic but... here goes.
If I decide to embed some kind of scripting language like Lua or Ruby into a C++ program by linking it's interpreter what does that allow me to do in C++ then?
Would I be able to write Ruby or Lua code right into the cpp file or simply call scripts from the program?
If the latter is true, how would I do that?
Because they're scripting languages, the code is always going to be "interpreted." In reality, you aren't "calling" the script code inside your program, but rather when you reach that point, you're executing the interpreter in the context of that thread (the thread that reaches the scripting portion), which then reads the scripting language and executes the applicable machine code after interpreting it (JIT compiling kind of, but not really, there's no compiling involved).
Because of this, its basically the same thing as forking the interpreter and running the script, unless you want access to variables in your compiled program/in your script from the compiled program. To access values to/from, because you're using the thread that has your compiled program's context, you should be able to store script variables on the stack as well and access them when your thread stops running the interpreter (assuming you stored the variables on the stack).
Edit: response:
You would have to write it yourself. Think about it this way: if you want to use assembly in c++, you use the asm keyword. You then in the c++ compiler, need to parse the source file, get to the asm keyword, and then switch to the assembly compiler. Then the assembly compiler needs to go until the end bracket of the asm region and compile this code.
If you want to do this,it will be a bit different, since assembly gets compiled, not interpreted (which is what you want to do). What you'll need to do, is change the compiler you're using (lets say c++), so that it recognizes your own user defined keyword. Lets say this keyword is scriptX{}. You need to change the c++'s parser so that when it see's scriptX{}, it stores everything between the brackets in the readonly data section of your compiled program. You then need to add a hook in the compiled assembly file to switch the context of the thread to your script interpreter, and start the program counter at the beginning of your script section (which you put in read only data section of the object file).
Good luck with that...
A common reason to embed a scripting language into a program is to provide for the ability to control the program with scripts provided by the end user.
Probably the simplest example of such a script is a configuration file. Assume that your program has options, and needs to remember the options from run to run. You could write them out to a file as a binary image of your options structure, but that would be fragile, not easy to inspect or edit, and likely not portable across systems. Writing the options out in plain text with some sort of labels for which is which addresses most of those complaints, but now you need to parse that text and recover the options. Then some users want different options on Tuesdays, want to do simple arithmetic to compute one option from another, or to write one configuration file that they can use on both Windows and Linux, and pretty soon you find yourself inventing a little language to express all of those ideas and mechanisms with. At this point, there's a better way.
The languages Lua and TCL both grew out of essentially that scenario. Larger systems needed to be configured and controlled by end users. End users wanted to edit a simple text file and get immediate satisfaction, even (especially) when working with large systems that might have required hours to compile successfully.
One advantage here is that rather than inventing a programming language one feature at a time as user's needs change, you start with a complete language along with its documentation. The language designer has already made a number of tough decisions for you (how do I represent strings and numbers, what about lists, what about named values, what does if look like, etc.) and has generally also brought a carefully designed and debugged implementation to the table.
Lua is particularly easy to integrate. Reading a simple configuration file and extracting the settings from the Lua state can be done using a small subset of its C API. Once you have Lua available, it is attractive to use it for other purposes. In many cases, you will find that it is more productive to write only the innermost loops in C, and use Lua to glue those functions together and provide all the "business logic" of the application. This is how Adobe Lightroom is implemented, as well as many games on platforms ranging from simple set-top-boxes to iOS devices and even PCs.
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.