Catching exceptions under Linux from dynamicly loading libraries

This problem happened with gcc version 3.2.3 (Red Hat Linux 3.2.3). By default g++ doesn’t produce the code which allows to catch exceptions thrown from the shared library.

Thus additional flag is required for the compiler: -fdynamic.

Here is the example.

Here are two projects: testapp and testlib.

Compiler flags for the testapp: -fdynamic

Linker flags for the testapp (here is only location for the ACE libs): -L/ace/lib -Wl -lACE

Compiler flags for the testlib: -fdynamic

Linker flags for the testlib: -shared -o testlib.so -Wl -lACE

//-------------------------
//testlib.cpp
//-------------------------
#define ACE_BUILD_SVC_DLL

#include <string>
#include <iostream>
#include "/ace/src/svc_export.h"

using namespace std;

class CException{
public:
	string m_str;
public:
	virtual void test(){
		m_str = "hello";
		cout << m_str << endl;
	}
};

extern "C" ACE_Svc_Export int test(){
	throw CException();
	return 0;
}

//-------------------------
//testapp.cpp
//-------------------------

#include <iostream>
#include "/ace/src/DLL_Manager.h"

using namespace std;
class CException{
public:
	string m_str;
public:
	virtual void test(){
		m_str = "hello";
		cout << m_str<<endl;
	}
};

int main(){

	ACE_DLL_Manager * pMan = ACE_DLL_Manager::instance();
	ACE_DLL_Handle * hDll =
	pMan->open_dll("../testlib/testlib.so",
	ACE_DEFAULT_SHLIB_MODE, 0);
	if (!hDll) cout << "not openeded: " << errno << endl;

	try{
		typedef int *(* PTR_FUNC)();
		PTR_FUNC pFunc  = (PTR_FUNC) hDll->symbol("test", 1);
		(pFunc)();
	}catch(CException & exp){
		exp.test();
		cout << "exception caught!";
	}

}


In this example the ACE library is used to open shared library.

Leave a Reply