Reputation: 2567
Is it possible through some linker magic to link together two files with two separate main()
s, then add a third controlling main()
that would decide at run time which of the other two mains to call?
So imagine:
/* test1.c */
include <stdio.h>
int main()
{
printf("Test1\n");
}
/* test2.c */
include <stdio.h>
int main()
{
printf("Test2\n");
}
/* controller.c */
int main()
{
int x;
// x gets set somehow
if (x == 1)
// call main from test1.c
else if (x == 2)
// call main from test2.c
}
I realize that this may be a weird question, but I'm trying to work around a constraint on a Cray supercomputer that allows me to run only a single executable per node. And I explicitly don't want to modify test1.c
and test2.c
.
Upvotes: 1
Views: 103
Reputation: 2499
You could try it with PIEs and dynamic linking:
/* controller.c */
#include <stdio.h>
#include <errno.h>
#include <dlfcn.h>
int main(int argc, char *argv[])
{
int retval, (*pmain)(int argc, char *argv[]);
void *prg = dlopen(argv[1], RTLD_LAZY);
pmain = dlsym(prg, "main");
retval = (*pmain)(argc - 1, &argv[1]);
dlclose(prg);
return retval;
}
Compile and run, it works on my Linux:
gcc controller.c -o controller -ldl
gcc -fPIE -pie -Wl,--export-dynamic test1.c -o test1
gcc -fPIE -pie -Wl,--export-dynamic test2.c -o test2
./controller ./test1
Test1
./controller ./test2
Test2
Upvotes: 2
Reputation: 409136
In short, there's no possible way. Not directly anyway.
A possible solution is to use e.g. system
(or fork
and exec
yourself) to run the specific program externally in a new process.
Another solution is to put the functionality from the different main
functions in separate functions, and have main
be conditionally compiled in if a specific preprocessor macro is defined, and the main
functions just call the special functions that do the actual work.
Upvotes: 0