My question is: I have a long string that contains a compilable C++ code.
The C++11 standard does not mention any function able to do that (compile C++ code in some string). And I know no library (except perhaps libclang, but I don't know if it able to compile a string) able to do that.
Actually, a C++ compiler practically needs to make a lot of optimizations (if you want the code to run not too slowly), so will spend some significant time (relative to computer speed, e.g. several tenth of seconds even for a small C++ source code) to compile your generated C++ code. And heavily templatized C++ code may take a lot of time (even an infinite amount in pathological cases, since C++ templates are accidentally Turing Complete) to be compiled.
So practically speaking, you gain no advantage to not writing a C++ source file. Some compilers (e.g. GCC on Linux with g++ -x c++ /dev/stdin
) are able to compile C++ code from their standard input, so you could use (on POSIX systems) popen to feed them.
Just write your C++ code into some temporary C++ source file (perhaps in some tmpfs file system, if you want to avoid disk IO) or perhaps a pipe(7) or fifo(7)... and fork a compilation. On Linux and Posix systems, you could compile (e.g. with g++ -Wall -fPIC -O -shared /tmp/temporary1234.cc -o /tmp/temporary1234.so
) that code to a "plugin" or shared object that your main program could later dlopen
If you are generating the C++ code, you could consider using (instead of generating C++ source then compiling it), some Just-In-Time compilation library like gccjit, LLVM, libjit, lightning, asmjit etc... Then you'll generate some AST-like internal representation (specific to the JIT library!) of the code.