1

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;
}
Yuri Albuquerque
  • 474
  • 3
  • 14

2 Answers2

3

On most UNIX platforms, libc contains the implementations of basic system call wrappers, like read(), write(), and _exit(). These functions are used by all applications, including ones which are written in C++. Indeed, the implementations of many C++ standard library functions will make use of these wrappers -- for example, using the << operator on std::cout will call the libc implementation of write().

So: probably not. If you're on any kind of UNIX system, libstdc++ will depend on libc, so you'll need to link against libc. (Windows is a rather different situation, but it doesn't sound like that's what you're using.)

  • The C++ standard includes most of the C standard library. So it's kind of a dependency and technically it's part of the C++ standard library. – Nikos C. Aug 01 '19 at 03:51
3

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.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • I think [referring to the C++ standard library as the "STL" might not be entirely correct](https://stackoverflow.com/q/5205491/9254539). – eesiraed Aug 01 '19 at 05:51
  • @AlexanderZhang It's been retrofitted by convention to mean "**St**andard **L**ibrary, because most people just call it STL. Writing "C++ standard library" every single time is just tiring. When people say "STL" these days, they don't refer to Stepanov's library. – Nikos C. Aug 01 '19 at 06:05