Zum Hauptinhalt springen

C++ - Linux Shared Object

 1// Literatur: Vorlesungsunterlagen ASD3 von Thomas Scheidl (FH-Hagenberg) 
 2//            http://linux.die.net/man/
 3
 4
 5//executable.cpp:
 6//-------------------------------------------------------------------
 7	#include <iostream>
 8	#include <dlfcn.h>
 9
10	using namespace std;
11
12	typedef void (*Test)();
13
14	int main()
15	{
16		void *lib = dlopen("./sharedobject.so", RTLD_NOW);
17
18		if (lib != 0)
19		{
20			Test f1 = reinterpret_cast<Test>(dlsym(lib, "Test"));
21
22			if (f1 != 0)
23			{
24				f1();
25			}
26			else
27			{
28				cout << dlerror() << endl;
29				cout << "failed get function pointer" << endl;
30			}
31
32			dlclose(lib);
33		}
34		else
35		{
36			cout << "failed loading .so" << endl;
37		}
38	}
39
40//sharedobject.cpp:
41//-------------------------------------------------------------------
42	#include <iostream>
43
44	using namespace std;
45
46	extern "C" void Test()
47	{
48		cout << "Test" << endl;
49	}
50
51//Makefile:
52//-------------------------------------------------------------------
53	main: SO EXC
54
55	SO: sharedobject.cpp
56		g++ -shared -o sharedobject.so sharedobject.cpp
57
58	EXC: executable.cpp
59		g++ -o executable executable.cpp -ldl
60
61	clean:
62		rm -f *.o