Question

I want investigate how is it possible to link C++ program without libstdc++, but with support of rtti. I tried compile it in the way described below. Any necessary but absent symbol I can define like function strcmp in the example, but is it possible to define typeinfo symbols without explicit mangle/demangle magic? And if possible how?

cd /tmp && cat << 'eof' >rtti.cpp && g++ -nodefaultlibs -lc rtti.cpp

extern "C" int strcmp(const char *s1, const char *s2) { return 0; };
#include "typeinfo"

int main(){
    return typeid(int) == typeid(char);
}

Linker says:

/tmp/cc6rBAef.o: In function `main':

rtti.cpp:(.text+0x18): undefined reference to `typeinfo for char'
rtti.cpp:(.text+0x1d): undefined reference to `typeinfo for int'
collect2: error: ld returned 1 exit status

So, how can I define 'typeinfo of char'(_ZTIc@@CXXABI_1.3) in source file using g++ or clang++?

PS. Don't ask me why do I need it. Just a curiosity.

Was it helpful?

Solution 2

Thanks to gcc community for hint.

The answer is:

"gcc use some magic to substitute destructor of __fundamental_type_info to a set of typeinfo symbols"

Substitution code is placed in file: gcc-4.7.2/gcc/cp/rtti.c, void emit_support_tinfos(void);

rtti.cc:

#include <typeinfo>
namespace __cxxabiv1 {
class __fundamental_type_info:public std::type_info{
public:
     explicit __fundamental_type_info(const char* __n) : std::type_info(_n) { } 
     virtual ~__fundamental_type_info(){}; 
};
}
int main(){
    return typeid(int) == typeid(char);
}

All fundamental typeinfos are inserted into object file during compilation.

$g++ -c ./rtti.cc;readelf -sW ./rtti.o |c++filt|grep typeinfo|wc -l

$153

So the question is answered.

OTHER TIPS

Since the symbols needed for RTTI seem to be in the libstdc++ library, you cannot do completely without it. Note that I found this by running

readelf -Ws `g++ -print-file-name=libstdc++.so` | awk '{print $8}' | c++filt | grep 'typeinfo for'

What you can do, however, is statically link with libstdc++:

g++ -static-libstdc++ rtti.cpp

In this way, you won't have any dynamic dependencies on libstdc++ and only the symbols you actually need are pulled in to your executable. (Well, all symbols from the object file that contains the needed symbols, fundamental_type_info.o in you example, I suppose.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top