Tuesday, October 26, 2021

[SOLVED] Is it possible to create a C ++ program, just linking to libcstdc ++, without linking to libc?

Issue

I'm starting to study c ++, and I got a doubt, when I use the ldd program and see the dependencies of the dynamic libraries, notice that besides the c++ standard library which is libstdc ++, libc is also compiled, and it is possible to make a program executable without libc, only with libstdc ++?

How to compile this code withou?

#include <iostream>

int main(void) {
    std::cout << "AAA";
    return 0;
}

Solution

The majority of the C standard library functions are actually also part of the C++ standard library ("STL" for short.) The <cstdlib> header for example, which provides functions like std::malloc() and std::system(), is part of the STL.

Note that even if you didn't ever use one of those functions explicitly, the STL will still make use of them as an implementation detail. std::copy() for example might call std::memcpy(). Comparing two std::string objects might result in a call to std::memcmp().

The compiler itself will do so too in many cases. new for example might result in a call to std::malloc(), and delete might call std::free(). Or if a noexcept function throws, the C++ standard says that std::terminate() will be called, which in turn is defined as calling std::abort() by default, which is a C library function from <cstdlib>.

Most C++ compiler and library implementations will simply re-use the C library rather than re-implement it. In other words, libc can be considered part of libstdc++ from the perspective of a C++ program. It just happens to be split into a separate library file. So if you link against libstdc++, you also need to link against libc.



Answered By - Nikos C.