Why dynamic_cast doesn't work ?

来源:互联网 发布:相机透视软件 编辑:程序博客网 时间:2024/05/17 09:34

Quote from: http://gcc.gnu.org/faq.html#dso

dynamic_cast, throw, typeid don't work with shared libraries

The new C++ ABI in the GCC 3.0 series uses address comparisons,rather than string compares, to determine type equality. This leadsto better performance. Like other objects that have to be present in thefinal executable, these std::type_info objects have whatis called vague linkage because they are not tightly bound to any oneparticular translation unit (object file). The compiler has to emitthem in any translation unit that requires their presence, and thenrely on the linking and loading process to make sure that only one ofthem is active in the final executable. With static linking all ofthese symbols are resolved at link time, but with dynamic linking,further resolution occurs at load time. You have to ensure thatobjects within a shared library are resolved against objects in theexecutable and other shared libraries.

  • For a program which is linked against a shared library, no additionalprecautions are needed.
  • You cannot create a shared library with the "-Bsymbolic"option, as that prevents the resolution described above.
  • If you use dlopen to explicitly load code from a sharedlibrary, you must do several things. First, export global symbols fromthe executable by linking it with the "-E" flag (you willhave to specify this as "-Wl,-E" if you are invokingthe linker in the usual manner from the compiler driver, g++).You must also make the external symbols in the loaded libraryavailable for subsequent libraries by providing the RTLD_GLOBALflag to dlopen. The symbol resolution can be immediate orlazy.

Template instantiations are another, user visible, case of objectswith vague linkage, which needs similar resolution. If you do not takethe above precautions, you may discover that a template instantiationwith the same argument list, but instantiated in multiple translationunits, has several addresses, depending in which translation unit theaddress is taken. (This is not an exhaustive list of the kindof objects which have vague linkage and are expected to be resolvedduring linking & loading.)

If you are worried about different objects with the same namecolliding during the linking or loading process, then you should usenamespaces to disambiguate them. Giving distinct objects with globallinkage the same name is a violation of the One Definition Rule (ODR)[basic.def.odr].

For more details about the way that GCC implements these and otherC++ features, please read the C++ ABI specification.Note the std::type_info objects which must beresolved all begin with "_ZTS". Refer to ld'sdocumentation for a description of the "-E" &"-Bsymbolic" flags.