I wrote this off the top of my head - no guarantee that it will even compile, but it's probably pretty close. Good enough for an interview.
#include <stdio.h>
#include <unistd.h>
char *program = "#include<stdio.h>\
\
void Func1() { printf("hi\n"); }\
void Func2() { printf("hello\n"); }\
void Func3() { printf("hey\n"); }\
main() {\
";
char *program1 = "}\n";
static in ContainsFunction(char *func)
{
char *match = strstr(func, program);
if (!match || match - program < 5)
return 0;
int len = strlen(func);
return strcmp(match-5, program) == 0 && match[len + 1] == '(' && isalnum(func[len-1]);
}
static void Compile(char *prog)
{
pid_t pid = fork();
if (pid == 0) {
execl("/usr/bin/gcc", "gcc", prog, (char *)0);
}
else if (pid < 0) { printf("fork fail\n"); }
else {
pid_t ws = wait();
}
}
static void Execute(char *prog)
{
pid_t pid = fork();
if (pid == 0) {
execl(prog, prog, (char *)0);
}
else if (pid < 0) { printf("fork fail\n"); }
else {
pid_t ws = wait();
}
}
static void CallFunction(char *funcname)
{
FILE *fp = fopen("foo.c", "w");
fputs(program, fp);
fprintf(fp, "\t%s();\n", funcname);
fputs(fp, program1);
fclose(fp);
Compile("foo.c");
Execute("a.out");
}
int main()
{
char funcname[8192]; /* too small, fail */
puts("Who ya gonna call?");
gets(funcname);
if (ContainsFunction(funcname)) { CallFunction(funcname)); }
else { printf("fail - no function %s\n", funcname); }
}