You'll probably have to resort to loading the external libraries at run time.
If you're on Linux, you can use dlopen
to open a library at runtime, then use dlsym
to extract each variable and function you would want to use.
You could create a struct that would contain pointers to the variables and functions for an instance of the library, then populate a copy of the struct for each variation of the library. From there, you would use the function pointer from the appropriate struct instance to call a particular library function.
For example, suppose you have the following library files:
x2.c:
#include <stdio.h>
void foo()
{
printf("in x2 foo
");
}
x3.c
#include <stdio.h>
void foo()
{
printf("in x3 foo
");
}
And these are compiled into libx2.so and libx3.so respectively. Then your main source could do this:
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
struct lib {
void (*foo)(void);
};
int main(void)
{
struct lib lib2;
struct lib lib3;
void *l2 = dlopen("./libx2.so", RTLD_NOW);
if (!l2) {
printf("dlopen x2 failed: %s
", dlerror());
exit(1);
}
void *l3 = dlopen("./libx3.so", RTLD_NOW);
if (!l3) {
printf("dlopen x3 failed: %s
", dlerror());
exit(1);
}
lib2.foo = dlsym(l2, "foo");
lib3.foo = dlsym(l3, "foo");
lib2.foo();
lib3.foo();
dlclose(l2);
dlclose(l3);
return 0;
}
Output:
in x2 foo
in x3 foo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…