Create function with name from (Char*) ?

I need to create a function with name from const char *


Like createFunc("makeMe");

lead to the creation of makeMe();

Is this possible ?
No.

Well, sort of.

You need a macro.
1
2
3
4
5
6
#define createFunc(x) base##x

int createFunc(makeMe)()
{
    return 0;
}


... or something like that. The prefix base is optional.
closed account (o1vk4iN6)
You can't create a new function after it's been compiled, if that's what you are trying to do. If you want to name a function "makeme", than define a function the normal way with "makeme". If you want to use a string as an identifier to which function to use that's possible, but inefficient.
You can't create a new function after it's been compiled
That's the point of using a macro as it processed before the code is compiled.
Try instead dynamicall binding of functions, may be some thing like
http://www.cplusplus.com/forum/general/61609/

you can change the struct as following

1
2
3
4
5
6
7
8
9
10
11
12
struct createFunc {

	char*	name;

	void(*func)();

	createFunc(void(*func)(), char* name) {
		strcpy( this->name , name );
		this->func = func;
         }

};


strore the created functions , dynamicall binded functions , in an array of type createFunc, createFunc functions[] and at the run time you can go through a loop and call the right function by name

1
2
3
4
5
6
7
8
int funCount = sizeof(functions) / sizeof(createFunc );

		for (int i = 0; i < funCount; i++) {
			if (strcmp(function2BeCalled, functions[i].name) == 0) {
				functions[i].func();
				return;
			}
		}




hope it helps
Last edited on
Topic archived. No new replies allowed.