您的位置:首页 > 其它

Why dynamic_cast doesn't work ?

2010-04-26 17:53 309 查看

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 leads
to better performance. Like other objects that have to be present in the
final executable, these
std::type_info

objects have what
is called vague linkage because they are not tightly bound to any one
particular translation unit (object file). The compiler has to emit
them in any translation unit that requires their presence, and then
rely on the linking and loading process to make sure that only one of
them is active in the final executable. With static linking all of
these symbols are resolved at link time, but with dynamic linking,
further resolution occurs at load time. You have to ensure that
objects within a shared library are resolved against objects in the
executable and other shared libraries.

For a program which is linked against a shared library, no additional
precautions 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 shared
library, you must do several things. First, export global symbols from
the executable by linking it with the "
-E

" flag (you will
have to specify this as "
-Wl,-E

"
if you are invoking
the linker in the usual manner from the compiler driver,
g++

).
You must also make the external symbols in the loaded library
available for subsequent libraries by providing the
RTLD_GLOBAL

flag to
dlopen


. The symbol resolution can be immediate or
lazy.

Template instantiations are another, user visible, case of objects
with vague linkage, which needs similar resolution. If you do not take
the above precautions, you may discover that a template instantiation
with the same argument list, but instantiated in multiple translation
units, has several addresses, depending in which translation unit the
address is taken. (This is not
an exhaustive list of the kind
of objects which have vague linkage and are expected to be resolved
during linking & loading.)

If you are worried about different objects with the same name
colliding during the linking or loading process, then you should use
namespaces to disambiguate them. Giving distinct objects with global
linkage 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 other
C++ features, please read the C++ ABI specification
.
Note the
std::type_info

objects which must
be
resolved all begin with "_ZTS". Refer to
ld

's
documentation for a description of the "
-E

" &
"
-Bsymbolic

" flags.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: