I want to compile a C++ program so that it dynamically links to libc, but does not have a dynamic dependency on libstdc++. for example 'hello world' using std::cout, when compiled with the -static-libstdc++ -flto
flags, the output executable file is 1 MB in size (Arch linux amd64). I want an effect similar to using build-std
in rust, so that the 'hello world' program takes up space the same whether using std::cout or using printf.
C++'s iostream library, including std::cout
, is a huge library.
If you are using it, you either need to link to a dynamic library that contains the huge library, or you need to statically link it and include the huge library in your executable.
It isn't plausible for the C++ compiler to eliminate it and translate everything down to C calls sadly.
There is a chance that if you recompiled the entire C++ chain of libraries and used link time optimization your compiler could aggressively work out a way to reduce it to C calls, but even that is unlikely - the relative complexity of iostreams is high, with lots of internal virtual classes, all of which would require a fair amount of luck to optimize out completely.
Now, this isn't true of other parts of the C++ standard library; many of them could plausibly optimize away, like the standard container and most of the algorithms library. It is just that iostreams is, frankly, bloated and not that well designed, especially with your goals in mind. It was an early C++ library and it was decades ago.