要点
- C++の関数はマングリングされるので extern("C") が必要。
- 読み込まれる側はコンパイルオプションに -shared が必要。
- 読み込む側はコンパイルオプションに -ldl が必要。
- ライブラリのパスを設定する方法は色々あるがインラインでLD_LIBRARY_PATHに設定するのが楽。
実装
昔の人は「論よりRun」と言ったぜ。やれば分かるさ。
French.cxx
#include <stdio.h>
extern "C"
{
void hello();
}
void hello()
{
printf("Bonjour\n");
}
main.cxx
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char * * argv)
{
void * dl = dlopen(argv[1], RTLD_LAZY);
if (! dl)
{
exit(1);
}
void (* f)();
f = (void (*)()) dlsym(dl, "hello");
if (f)
{
(* f)();
}
else
{
printf("something went wrong\n");
}
dlclose(dl);
return 0;
}
Makefile
run: main.exe libFrench.so
LD_LIBRARY_PATH=. ./main.exe libFrench.so
main.exe: main.cxx
clang++ -o main.exe main.cxx -ldl
libFrench.so: French.cxx
clang++ -shared -o libFrench.so French.cxx
clean:
rm -rf *.exe *.o *.so