I am trying to run my C++ program on other Mac OSX machines which may have an older copy of libstdc++, but have all the other tools. I tried to follow this approach, also mentioned in this SO question, even though it discusses a linux setup. I have small program try.cpp:
#include <iostream>
int main() {
int a = 10;
std::cout << a << '\n';
return 1;
}
Obviously, if I just compile it, I get
$ /usr/bin/g++ try.cpp
$ otool -L a.out
a.out:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
I understand the dependency on libSystem.B.dylib, and we can leave that aside. To try to get rid of libstdc++, I try this:
$ /usr/bin/g++ try.cpp /usr/lib/libstdc++-static.a
$ otool -L a.out
a.out:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
So, I try
$ ln /usr/lib/libstdc++-static.a .
$ /usr/bin/g++ try.cpp -L.
$ otool -L a.out
a.out:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
or,
$ /usr/bin/g++ try.cpp -L. -lstdc++-static
$ otool -L a.out
a.out:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
Finally, this works:
$ /usr/bin/gcc try.cpp -L. -lstdc++-static
$ otool -L a.out
a.out:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
Is this alright? (To use gcc to link C++ programs with libstdc++). I've heard somewhere that g++ is actually a script that uses gcc and libstdc++ to compile C++ programs. If that is the case, and we use it correctly, it should be ok.
However, I am actually using the macport compiler and a more complicated program, for which gcc generates some warnings, while it is C++ compliant. Something to the effect of:
ld: warning: std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >::~basic_stringbuf() has different visibility (hidden) in /opt/local/lib/gcc44/libstdc++.a(sstream-inst.o) and (default) in /var/folders/2u/2uLPtE+3HMi-BQIEfFVbSE+++TU/-Tmp-//ccoE2rqh.o
This suggests that we shouldnt be using gcc for c++ compilations. So to sum up, the questions are:
- How to link libstdc++ statically
- If g++ doesn't do it, is it ok to use gcc and supply the libstdc++ manually? Then why the visibility warnings?
- If neither of the two approaches work because of the visibility problems in the compiled libraries, why not use libstdc++ source files (sstream.h, list.h, vector.c) etc and just include them in the compilation. Even though this will make the compilation slow, it might be useful for certain applications. It might even lead to better optimization!