C++ - Linux Shared Object | wedi

You are here

C++ - Linux Shared Object

// Literatur: Vorlesungsunterlagen ASD3 von Thomas Scheidl (FH-Hagenberg) 
//            http://linux.die.net/man/
 
 
//executable.cpp:
//-------------------------------------------------------------------
	#include <iostream>
	#include <dlfcn.h>
 
	using namespace std;
 
	typedef void (*Test)();
 
	int main()
	{
		void *lib = dlopen("./sharedobject.so", RTLD_NOW);
 
		if (lib != 0)
		{
			Test f1 = reinterpret_cast<Test>(dlsym(lib, "Test"));
 
			if (f1 != 0)
			{
				f1();
			}
			else
			{
				cout << dlerror() << endl;
				cout << "failed get function pointer" << endl;
			}
 
			dlclose(lib);
		}
		else
		{
			cout << "failed loading .so" << endl;
		}
	}
 
//sharedobject.cpp:
//-------------------------------------------------------------------
	#include <iostream>
 
	using namespace std;
 
	extern "C" void Test()
	{
		cout << "Test" << endl;
	}
 
//Makefile:
//-------------------------------------------------------------------
	main: SO EXC
 
	SO: sharedobject.cpp
		g++ -shared -o sharedobject.so sharedobject.cpp
 
	EXC: executable.cpp
		g++ -o executable executable.cpp -ldl
 
	clean:
		rm -f *.o