Suppose you created a main() to deal with an exercise you asked your students.
Every student is supposed to write their own function, with the same API. And a single file will be created, with all functions and the main calling them.
Lets say: int studentname(int a, int b) is the function pattern.
One way I deal with it was using a vector of pointer to functions int (*func[MAX])(). But you need to fulfill the vector one by one func[0]=studentname;.
I wonder, is there a way a function can be called by its name somehow?
Something like: int student1(int a , int b), student2(), etc.
And in main somehow we could just call sscanf(funcname,"student%d",i); funcname();.
Do you have any other idea? Maybe
int studentname(int a, int b, char *fname)
{
strcpy(fname, "studentname");
Anything creative will do! 🙂
Thanks!
Beco
PS. I tried just a vector of functions, but C won’t allow me! 🙂
int func[2]()={{;},{;}};
This way I could just give to each student a number, and voilá… But no way. It was funny though.
Edited: I’m using linux.
Edited 2: Thanks! I’ve accepted an answer that helped me, but I’ve also documented a complete example as an answer bellow.
Maybe a bit overcomplicating it, but spontaneous idea:
As an alternative:
And yet another idea:
extern "C". Depending on the implementation this might look a bit confusing and overcomplicated though.Example for the approach with
dlopen()anddlsym()(whether only one function per library or all – doesn’t matter):