我正在构建一个共享库f-no-rtti
。在内部,这个库抛出std:invalid_argument
并捕获std::exception
,但是catch
从未输入子句。
以下代码重现了该问题(g++ 4.2、Mac OS X 10.6):
// library.cpp: exports f(), compiled with -fno-rtti
#include <stdexcept>
#include <iostream>
extern "C" {
void f() {
try {
throw std::invalid_argument("std::exception handler");
} catch( std::exception& e) {
std::cout << e.what() << "\n";
} catch(...) {
std::cout << "... handler\n";
}
}
}
// main.cpp: the main executable, dynamically loads the library
#include <dlfcn.h>
typedef void(*fPtr)();
int main() {
void* handle = dlopen( "./libexception_problem.dylib", RTLD_LAZY );
fPtr p_f = reinterpret_cast<fPtr>( dlsym( handle, "f" ) );
p_f();
}
Output:
MacBook-Pro:teste pfranco$ # works fine with rtti
MacBook-Pro:teste pfranco$ g++ -c library.cpp && g++ -shared -o libexception_problem.dylib library.o && g++ main.cpp -o main && ./main
std::exception handler
MacBook-Pro:teste pfranco$ # breaks with -fno-rtti
MacBook-Pro:teste pfranco$ g++ -c -fno-rtti library.cpp && g++ -shared -o libexception_problem.dylib library.o && g++ -fno-rtti main.cpp -o main && ./main
... handler
MacBook-Pro:teste pfranco$ #-no_dead_strip_inits_and_terms doesn't change anything
MacBook-Pro:teste pfranco$ g++ -c -no_dead_strip_inits_and_terms -fno-rtti library.cpp && g++ -no_dead_strip_inits_and_terms -shared -o libexception_problem.dylib library.o && g++ -fno-rtti -no_dead_strip_inits_and_terms main.cpp -o main && ./main
... handler
MacBook-Pro:teste pfranco$ # linking against the shared library works, but this isn't always an option
MacBook-Pro:teste pfranco$ g++ -c -fno-rtti library.cpp && g++ -shared -o libexception_problem.dylib library.o && g++ -fno-rtti main.cpp -o main -L. -lexception_problem && ./main
std::exception handler
仅当抛出的代码位于共享库,并且仅当捕获的类型是基类实际异常的情况 -catch(std::invalid_argument&)
工作正常,std::logic_error&
没有。
有趣的是,这在 Linux 上不会发生,即使运行完全相同的命令。
问题:
- 为什么会出现这种情况?这是一个错误、未定义的行为还是设计使然?
- 如果没有链接到图书馆,我怎样才能让它工作?
多谢。