#include <dlfcn.h>
#include <iostream>
using namespace std;
int main()
{
// open module
void *module = dlopen("hello.o", RTLD_LAZY);
if(!module)
{
cerr << "error in open: " << dlerror() << "\n";
exit(-1);
}
// can this next 4 lines be done in a simpler way?
typedef void (*Function)();
Function function;
void *pointer = dlsym(module, "hello");
function = *reinterpret_cast<Function*>(&pointer);
// check for errors
const char *error = dlerror();
if(error)
{
cerr << "fatal error: " << error << "\n";
exit(-1);
}
// call the function
(*function)();
// close the module
dlclose(module);
return 0;
}
#include <iostream>
using namespace std;
// i think this needs to be wrapped in extern "C"
void hello()
{
cout << "hello\n";
}
genjix@linux:~/media/tmp/obj/dl> g++ dynamic.cpp -ldl
genjix@linux:~/media/tmp/obj/dl> g++ -c hello.cpp
genjix@linux:~/media/tmp/obj/dl> ./a.out
error in open: hello.o: cannot open shared object file: No such file or directory
also if i try using c object file
void hello()
{
printf("hello\n");
}
genjix@linux:~/media/tmp/obj/dl> g++ dynamic.cpp -ldl
genjix@linux:~/media/tmp/obj/dl> gcc -c helloc.c
genjix@linux:~/media/tmp/obj/dl> ./a.out
error in open: hello.o: cannot open shared object file: No such file or directory
why am I getting these errors?
interestingly if i open "./hello.o" I get this
genjix@linux:~/media/tmp/obj/dl> g++ dynamic.cpp -ldl
genjix@linux:~/media/tmp/obj/dl> ./a.out
error in open: ./hello.o: only ET_DYN and ET_EXEC can be loaded
...