Reputation: 8146
I was reading the stringizing operator (#) in c which does the token pasting what ever is being appended to it .I wanted to know is it possible to create a function(with void or non void arguments) dynamically using the stringizing operator (and Macros if possible - #define) . I want the following structure of the code :
#define #function_name(/*void or non void */) void function_name(/*void or non void */)
char *function_name;
scanf("%s",function_name);
something like this. Basically I am trying to create the function at runtime.
Upvotes: 2
Views: 2685
Reputation: 2207
C is a statically compiled language, as such it doesn't make creating functions during runtime easy, or even generally possible. You could write out the C code you need to a .c file, execute a compiler on the system, and then dynamically load the object library. In the course of writing out the initial .c file you could name the function what ever you wanted. In short though, using macros won't work to do what you want to do. And using the method I've just mentioned is a massive hack. Possible, but ill advised.
If you just want to rename a function, or choose from a limited set of functions you know in advance and can compile into the program, then you can use a function pointer. But this strikes me as the reverse of what you are trying to do, because the function pointer provides you with a static name (symbol) which can be used to call variable functions.
If you really need to rename a function pointer, you could keep an array of function pointers, and index them using a string mapping. Then call your functions by looking up their pointers via their strings (names). the string is of course mutable, so you can change the 'name' of your function. But this is a very roundabout route and I honestly can't see a good reason to do this.
Finally, the most useful and correct solution would be to implement a virtual machine with it's own symbol table. There are implementations out there already; Python and Slang spring to mind.
Upvotes: 0
Reputation: 5856
One hacky way of doing what you need (and chances are you are not going to be happy with that answer) is as follows:
C/C++ languages do not provide a mechanism to execute text as code on-a-fly (like JavaScript's eval("var i = 0;")
, for instance)
Upvotes: 4