compile and run c++ code runtime - c++

Does anyone know how to compile your c++ code wich you write while your program is already running?
And later i would like to run that code.
I want to do this because I am trying to make a game that woul teach you programing and so the user would have to write the code while the game is running and test it.
Thanks for any help

You'd have an easier time if you chose a language that was designed with embedding in mind - like LUA or python. For C++, you'd have to go for something extremely clumsy and fragile like invoking an external compiler (which is also a logistics nightmare when shipping your game), or something as complex as integrating a compiler in your game (probably doable with llvm components, but...)
Also, for "teaching programming", C++ probably isn't the best language :)

You have to call the compiler to compile and link the user-entered code. This has to be made either into an executable that is then run from another process you create, or as a library that you dynamically load and call.
How this is done is different on POSIX platforms (like Linux and OSX) and Windows.

Related

How interoperability works

I know that many large-scale applications such as video games are created using multiple langages. For example, it's likely the game/physics engines are written in C++ while gameplay tasks, GUI are written in something like Python or Lua.
I understand why this division of roles is done; use lower-level languages for tasks that require extreme optimization, tweaking, efficiency and speed, while using higher-level languages to speed up production time, reduce nasty bugs ect.
Recently, I've decided to undertake a larger personal project and would like to divy-up parts of the project similar to above. At this point in time, I'm really confused about how this interoperability between languages (especially compiled vs interpreted) works.
I'm quite familiar with the details of going from ANSCII code test to loading an executable, when written in something like C/C++. I'm very curious at how something like a video game, built from many different languages, works. This is a large/broad question, but specifically I'm interested in:
How does the code-level logic work? I.e. how can I call Python code from a C++ program? Especially since they don't support the same built-in types?
What does the program image look like? From what I can tell, a video game is running in a single process, so what does the runtime image look like when running a C/C++ program that calls a Python function?
If calling code from an interpreted language from a compiled program, what are the sequence of events that occur? I.e If I'm inside my compiled executable, and for some reason have a call to an interpreted language inside a loop, do I have to wait for the interpreter every iteration?
I'm actually finding a hard time finding information on what happening at the machine-level, so any help would be appreciated. Although I'm curious in general about interoperation of software, I'm specifically interested in C++ and Python interaction.
Thank you very much for any insight, even if it's just pointing me to where I can find more information.
In the specific case of python, you have basically three options (and this generally applies across the board):
Host python in C++: From the perspective of the C++ programme, the python interpreter is a C library. On the python side, you may or may not need to use something like ctypes to expose the C(++) api.
Python uses C++ code as DLLs/SOs - C++ code likely knows nothing of python, python definitely has to use a foreign function interface.
Interprocess communication - basically, two separate processes run, and they talk over a socket. These days you'd likely use some kind of web services architecture to accomplish this.
Depending on what you want to do:
Have a look at SWIG: http://www.swig.org/ It's a tool that aims to connect C/C++ code with Python, Tcl, Perl, Ruby, etc. The common use case is a Python interface (graphical or not) that will call the C/C++ code. SWIG will parse the C/C++ code in order to generate the interfaces.
Libpython: it's a lib that allows you to embed Python code. You have some examples here: http://docs.python.org/3.0/extending/embedding.html

build and run c++ within c++ -- c++ scripts (instead of lua)

Currently, I embed lua in my c++ code.
I wonder if the same is possible with c++. That way I can pass objects and use libraries within the script. to do this, I think I would need the following from the master c++ code:
execute the running of the script
compile the script
run the script
the script passes pointer to it's data objects
the script is done and the program uses the data objects.
is this possible? small example?
For me it is useful as I ran science calculation that I don't want to stop but i want to add functionality on the fly. I also see this being useful for servers in c++ that don't want to shut down but want to make a change.
You may choose to use some kind of C++ interpreter but they can't do every thing. C++ is one of the hardest to implement(if not that hardest) languages. Just think about macros, templates and every other thing that make C++ as powerful as we know they are really hard to parse and understand and beside all of that we have optimization that create such fast and thin codes for us, so how an interpreter can be such powerful and understand all of this? Even best known compilers may fail to understand all of the standard or at least have errors for understanding complicated C++ codes. In one of my projects that heavily use templates using MSVC 2010, it take about 10 minutes to compile the code! So interpreters usually simplify their task and only support a subset of full C++, so if you are cool with this use some interpreter. I never used one of them but I heard cint is good.
The other option is you have a free compiler like g++ and actually compile your code into some kind of shared library and then load it dynamically and call some functions from it based on some kind of configuration.

Using scripting language in C++

My question is a little bit stupid but I decided to ask advanced programmers like some of you. So I want to make a "dynamic" C++ program. My idea is to compile it and after compilation (maybe with scripting language like python) to change some how the code of the program. I know you will tell me that after the compilation I can not change the code but is there a way of doing that. Thank you!
You could design a modular architecture using plugins in external libraries. For example you could use the Command Pattern. That way you can dynamically load code that was generated after you main program. You would have to fix an interface though. Functions like GetProcAddress in the Windows api might be a good point to start.
For dynamic coding and rapid prototyping I recommend to have a look at Lua. The engine is very small and easy to integrate in your c++ program.
The only way to do that in C++ is to unload the DLL with the code to be
modified, modify the sources, invoke the compiler to regenerate the DLL,
and reload the DLL. It's very, very heavy weight, and it only works if
the compiler is present on the machines where the code is to be run.
(Usually the case under Unix, rarely the case with Windows.)
Interpreted languages like Python are considerably more dynamic; Python
has a built-in function to execute a string as Python code, for example.
If you need dynamically modifiable code, I'd suggest embedding Python in
your application, and using it for the dynamic parts.
Personally I have never played with re-compiling C++ during runtime, and I do not intend too. However I have been doing a lot of embedding of scripting languages lately.
Someone else mentioned the obvious first choice for embedding: Lua. Lua is a pretty popular language to embed and you will find a bunch of documentation about how to do it. Integrating it into the C++ will allow you to define behavior at runtime like you want.
What I am using is a wonderful langauge called Squirrel. It is a lot like Lua but with native object(class) support and C++-like syntax. I have managed to embed it into a C++ application, and through using the sqrat binding library both languages can share information easily.
I have squirrel building and initializing my UI. As a result, 0 compiling is required in order to craft and structure my UI for my game. I intend to take this a step further and use this gameplay-side in order to create similar behavior you are looking for(changing behavior at runtime through dynamic code usage)
I recommend Checking out squirrel here: http://www.squirrel-lang.org/
I plan on writing tutorials on how to embed squirrel and install the binding library, but I have not started on them yet. If I can remember, I will edit this post in the future (could be a few months) once I have completed them. In the meantime give it a shot yourself. You may find it to your liking.

Generating C++ code at runtime, compiling and running it

is there a multiplatform c++ compiler that could be linked into any software ?
Lets say I want to generate c++ code at runtime, compile it and run it.
I'm looking for a compact solution (bunch of classes), preferably LGPL/BSD licence :)
As far as I know it can be done in Java and c#. What about c++ ?
Well maybe one of the modules of CLang will be of help? It's not dry yet on the C++ side but certainly will be soon.
I don't know of any open source ones for C++, but if you want small and compact scripting and are not hung up on C++ LUA might be an option for you
I'd drop C++ altogether and use Google V8. If you wanted to use C++ because the people using your app only know this, they should have no difficulties going to javascript.
And it's damn fast. And Javascript is a cool language too.
I've done this years ago in Linux by generating C++-code into a file, compile it by shell execute (with gcc) and then linking in the generated library dynamically. The dynamic linking differs of course between platforms.
This kind of thing is much much harder in C++, because the language doesn't use a virtual machine (or "runtime") that abstracts machine specifics away.
You could look into gcc, it's under the GPL IIRC, and ports exist for all major platforms.
When we looked into scripting we chose AngelScript because of the similarity with C++.
V8 is great but it's certainly limited to some platforms, AngelScript is a lot easier to compile with and probably to learn (if you came from C++) and it has a zlib license.
http://www.angelcode.com/angelscript/

dynamic code compilation

I'm working on a program that renders iterated fractal systems. I wanted to add the functionality where someone could define their own iteration process, and compile that code so that it would run efficiently.
I currently don't know how to do this and would like tips on what to read to learn how to do this.
The main program is written in C++ and I'm familiar with C++. In fact given most of the scenarios I know how to convert it to assembly code that would accomplish the goal, but I don't know how to take the extra step to convert it to machine code. If possible I'd like to dynamically compile the code like how I believe many game system emulators work.
If it is unclear what I'm asking, tell me so I can clarify.
Thanks!
Does the routine to be compiled dynamically need to be in any particular language. If the answer to that question is "Yes, it must be C++" you're probably out of luck. C++ is about the worst possible choice for online recompilation.
Is the dynamic portion of your application (the fractal iterator routine) a major CPU bottleneck? If you can afford using a language that isn't compiled, you can probably save yourself an awful lot of trouble. Lua and JavaScript are both heavily optimized interpreted languages that only run a few times slower than native, compiled code.
If you really need the dynamic functionality to be compiled to machine code, your best bet is probably going to be using clang/llvm. clang is the C/Objective-C front end being developed by Apple (and a few others) to make online, dynamic recompilation perform well. llvm is the backend clang uses to translate from a portable bytecode to native machine code. Be advised that clang does not currently support much of C++, since that's such a difficult language to get right.
Some CPU emulators treat the machine code as if it was byte code and they do a JIT compile, almost as if it was Java. This is very efficient, but it means that the developers need to write a version of the compiler for each CPU their emulator runs on and for each CPU emulated.
That usually means it only works on x86 and is annoying to anyone who would like to use something different.
They could also translate it to LLVM or Java byte code or .Net CIL and then compile it, which would also work.
In your case I am not sure that sort of thing is the best way to go. I think that I would do this by using dynamic libraries. Make a directory that is supposed to contain "plugins" and let the user compile their own. Make your program scan the directory and load each DLL or .so it finds.
Doing it this way means you spend less time writing code compilers and more time actually getting stuff done.
If you can write your dynamic extensions in C (not C++), you might find the Tiny C Compiler to be of use. It's available under the LGPL, it's compatible for Windows and Linux, and it's a small executable (or library) at ~100kb for the preprocessor, compiler, linker and assembler, all of which it does very fast. The downside to that, of course, is that it can't compare to the optimizations you can get with GCC. Another potential downside is that it's X86 only AFAIK.
If you did decide to write assembly, TCC can handle that -- the documentation says it supports a gas-like syntax, and it does support X86 opcodes.
TCC also fully supports ANSI C, and it's nearly fully compliant with C99.
That being said, you could either include TCC as an executable with your application or use libtcc (there's not too much documentation of libtcc online, but it's available in the source package). Either way, you can use tcc to generate dynamic or shared libraries, or executables. If you went the dynamic library route, you would just put in a Render (or whatever) function in it, and dlopen or LoadLibrary on it, and call Render to finally run the user-designed rendering. Alternatively, you could make a standalone executable and popen it, and do all your communication through the standalone's stdin and stdout.
Since you're generating pixels to be displayed on a screen, have you considered using HLSL with dynamic shader compile? That will give you access to SIMD hardware designed for exactly this sort of thing, as well as the dynamic compiler built right into DirectX.
LLVM should be able to do what you want to do. It allows you to form a description of the program you'd like to compile in an object-oriented manner, and then it can compile that program description into native machine code at runtime.
Nanojit is a pretty good example of what you want. It generates machine code from an intermediate langauge. It's C++, and it's small and cross-platform. I haven't used it very extensively, but I enjoyed toying around just for demos.
Spit the code to a file and compile it as a dynamically loaded library, then load it and call it.
Is there are reason why you can't use a GPU-based solutions? This seems to be screaming for one.