Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a function dynamically, during runtime in C++?

C++ is a static, compiled language, templates are resolved during compile time and so on...

But is it possible to create a function during runtime, that is not described in the source code and has not been converted to machine language during compilation, so that a user can throw at it data that has not been anticipated in the source?

I am aware this cannot happen in a straightforward way, but surely it must be possible, there are plenty of programing languages that are not compiled and create that sort of stuff dynamically that are implemented in either C or C++.

Maybe if factories for all primitive types are created, along with suitable data structures to organize them into more complex objects such as user types and functions, this is achievable?

Any info on the subject as well as pointers to online materials are welcome. Thanks!

EDIT: I am aware it is possible, it is more like I am interested in implementation details :)

like image 952
dtech Avatar asked Jun 13 '12 13:06

dtech


1 Answers

Yes, of course, without any tools mentioned in the other answers, but simply using the C++ compiler.

just follow these steps from within your C++ program (on linux, but must be similar on other OS)

  1. write a C++ program into a file (e.g. in /tmp/prog.cc), using an ofstream
  2. compile the program via system("c++ /tmp/prog.cc -o /tmp/prog.so -shared -fPIC");
  3. load the program dynamically, e.g. using dlopen()
like image 168
Walter Avatar answered Sep 24 '22 14:09

Walter