1

I have a very simple .h/.cpp file pair:

// The .h
class MyClass {
  public:
    int MyProc();
  };

// The .cpp
int MyClass::MyProc() {
  return 0;
  };

It compiles nicely into a .o file. If I look into the .o with nm, I see

0000000000000000 T _ZN7MyClass6MyProcEv

just as expected. I can link it, etc., everything fine.

If I just change one line in the header to

virtual int MyProc();

the .o file becomes more complicated:

0000000000000000 T _ZN7MyClass6MyProcEv
0000000000000000 V _ZTI7MyClass
0000000000000000 V _ZTS7MyClass
0000000000000000 V _ZTV7MyClass
                 U _ZTVN10__cxxabiv117__class_type_infoE

by adding the Virtual object elements to it, again as expected. My problem is the Undefined last line. I know that it needs libstdc++, but I do not want to link it later, I want to include it in the .o (or .a) file, so if somebody links my .o (.a) file it does not need any external dependency. How can I do that?

jollytall
  • 117
  • 8
  • The RTTI information of `MyClass` is a derived class from the base class `__cxxabiv1::__class_type_info`. To avoid that external dependency, do not use virtual member functions, or disable RTTI. (I think this is an *implementation detail*, and not a C++ standard requirement.) – Eljay Oct 06 '21 at 13:48
  • try `gcc file.cc -lstdc++ -static-libstdc++` for more information see https://stackoverflow.com/a/44527954/1539100 – sorosh_sabz Oct 06 '21 at 13:49
  • `clang++ -fno-rtti -std=c++17 -c Jollytall.cpp && nm --demangle Jollytall.o` ... but the best way to avoid the problem is to distribute your source files (`*.h` and `*.cpp`) so the consumer can compile them with their compiler and their settings to avoid ODR. – Eljay Oct 06 '21 at 14:02
  • @sorosh_sabz I do not get your solution. It is already trying to make an executable and since there is no 'main' it runs into an error. I fI use -c, it does not link, so static linking does not help. Can I make it into a .a including already the static stdc++? – jollytall Oct 06 '21 at 14:46
  • According to https://micro.nicholaswilson.me.uk/post/31855915892/rules-of-static-linking-libstdc-libc-libgcc#:~:text=Statically%20linking%20to%20libstdc%2B%2B%20is%20fine.%20Optional%2C%20and,none%29.%20Therefore%2C%20I%20always%20statically%20link%20to%20libstdc%2B%2B.] it should be possible to link libstdc++ statically. In this case shared library should be shipped instead of of *.o. Note that it is risky, because if customer will use different version of libstdc++ in his code, application behavior will become unpredictable. – Dmitry Messerman Oct 06 '21 at 15:55
  • @Eljay Thanks, it works. If you make it an answer, it can be the approved one from my point of view. – jollytall Oct 06 '21 at 16:28

0 Answers0