Search code examples
c++headerdefinition

C++ STL and multiple definitions


While searching the doc on cppreference.com, I've seen that some features are defined multiple times in different headers...

For example: std::move (in <algorithm> and <utility>), std::size_t, etc (see below).

The page about std::size_t starts with this precision:

Defined in header <cstddef>
Defined in header <cstdio>
Defined in header <cstdlib>
Defined in header <cstring>
Defined in header <ctime>
Defined in header <cuchar>                (since C++17)
Defined in header <cwchar>

Why is this the case? And which header should one choose rather than any other?


Solution

  • Every standard library header needs to be self contained. If we want to use it, we are not to be forced into including anything else. Since all of the headers in the list you cite end up using size_t in some capacity, including them must also make size_t available. So it's standard mandated behavior.

    Mind you, that the wording in cppreference is a bit misleading. It's not that every header always defines the type alias. It's more than likely that the actual definition is in some internal implementation specific header, that all of those public headers include it themselves.

    So the behavior in essence, is that there is only ever one "true" definition of size_t. And you can get it by including any of the above headers.

    As for which one to choose? You can examine the synopsis of each header. If all you need is size_t then cstddef is the most minimal header that includes it.