• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. _using-libcxx:
2
3============
4Using libc++
5============
6
7.. contents::
8  :local:
9
10Usually, libc++ is packaged and shipped by a vendor through some delivery vehicle
11(operating system distribution, SDK, toolchain, etc) and users don't need to do
12anything special in order to use the library.
13
14This page contains information about configuration knobs that can be used by
15users when they know libc++ is used by their toolchain, and how to use libc++
16when it is not the default library used by their toolchain.
17
18
19Using a different version of the C++ Standard
20=============================================
21
22Libc++ implements the various versions of the C++ Standard. Changing the version of
23the standard can be done by passing ``-std=c++XY`` to the compiler. Libc++ will
24automatically detect what Standard is being used and will provide functionality that
25matches that Standard in the library.
26
27.. code-block:: bash
28
29  $ clang++ -std=c++17 test.cpp
30
31.. warning::
32  Using ``-std=c++XY`` with a version of the Standard that has not been ratified yet
33  is considered unstable. Libc++ reserves the right to make breaking changes to the
34  library until the standard has been ratified.
35
36
37Enabling experimental C++ Library features
38==========================================
39
40Libc++ provides implementations of some experimental features. Experimental features
41are either Technical Specifications (TSes) or official features that were voted to
42the Standard but whose implementation is not complete or stable yet in libc++. Those
43are disabled by default because they are neither API nor ABI stable. However, the
44``-fexperimental-library`` compiler flag can be defined to turn those features on.
45
46The following features are currently considered experimental and are only provided
47when ``-fexperimental-library`` is passed:
48
49* The parallel algorithms library (``<execution>`` and the associated algorithms)
50* ``std::stop_token``, ``std::stop_source`` and ``std::stop_callback``
51* ``std::jthread``
52* ``std::chrono::tzdb`` and related time zone functionality
53* ``std::ranges::join_view``
54
55.. warning::
56  Experimental libraries are experimental.
57    * The contents of the ``<experimental/...>`` headers and the associated static
58      library will not remain compatible between versions.
59    * No guarantees of API or ABI stability are provided.
60    * When the standardized version of an experimental feature is implemented,
61      the experimental feature is removed two releases after the non-experimental
62      version has shipped. The full policy is explained :ref:`here <experimental features>`.
63
64.. note::
65  On compilers that do not support the ``-fexperimental-library`` flag, users can
66  define the ``_LIBCPP_ENABLE_EXPERIMENTAL`` macro and manually link against the
67  appropriate static library (usually shipped as ``libc++experimental.a``) to get
68  access to experimental library features.
69
70
71Using libc++ when it is not the system default
72==============================================
73
74On systems where libc++ is provided but is not the default, Clang provides a flag
75called ``-stdlib=`` that can be used to decide which standard library is used.
76Using ``-stdlib=libc++`` will select libc++:
77
78.. code-block:: bash
79
80  $ clang++ -stdlib=libc++ test.cpp
81
82On systems where libc++ is the library in use by default such as macOS and FreeBSD,
83this flag is not required.
84
85
86.. _alternate libcxx:
87
88Using a custom built libc++
89===========================
90
91Most compilers provide a way to disable the default behavior for finding the
92standard library and to override it with custom paths. With Clang, this can
93be done with:
94
95.. code-block:: bash
96
97  $ clang++ -nostdinc++ -nostdlib++           \
98            -isystem <install>/include/c++/v1 \
99            -L <install>/lib                  \
100            -Wl,-rpath,<install>/lib          \
101            -lc++                             \
102            test.cpp
103
104The option ``-Wl,-rpath,<install>/lib`` adds a runtime library search path,
105which causes the system's dynamic linker to look for libc++ in ``<install>/lib``
106whenever the program is loaded.
107
108GCC does not support the ``-nostdlib++`` flag, so one must use ``-nodefaultlibs``
109instead. Since that removes all the standard system libraries and not just libc++,
110the system libraries must be re-added manually. For example:
111
112.. code-block:: bash
113
114  $ g++ -nostdinc++ -nodefaultlibs           \
115        -isystem <install>/include/c++/v1    \
116        -L <install>/lib                     \
117        -Wl,-rpath,<install>/lib             \
118        -lc++ -lc++abi -lm -lc -lgcc_s -lgcc \
119        test.cpp
120
121
122GDB Pretty printers for libc++
123==============================
124
125GDB does not support pretty-printing of libc++ symbols by default. However, libc++ does
126provide pretty-printers itself. Those can be used as:
127
128.. code-block:: bash
129
130  $ gdb -ex "source <libcxx>/utils/gdb/libcxx/printers.py" \
131        -ex "python register_libcxx_printer_loader()" \
132        <args>
133
134.. _include-what-you-use:
135
136include-what-you-use (IWYU)
137===========================
138
139libc++ provides an IWYU `mapping file <https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/IWYUMappings.md>`_,
140which drastically improves the accuracy of the tool when using libc++. To use the mapping file with
141IWYU, you should run the tool like so:
142
143.. code-block:: bash
144
145  $ include-what-you-use -Xiwyu --mapping_file=/path/to/libcxx/include/libcxx.imp file.cpp
146
147If you would prefer to not use that flag, then you can replace ``/path/to/include-what-you-use/share/libcxx.imp``
148file with the libc++-provided ``libcxx.imp`` file.
149
150.. _termination-handler:
151
152Overriding the default termination handler
153==========================================
154
155When the library wants to terminate due to an unforeseen condition (such as a hardening assertion
156failure), the program is aborted through a special verbose termination function. The library provides
157a default function that prints an error message and calls ``std::abort()``. Note that this function is
158provided by the static or shared library, so it is only available when deploying to a platform where
159the compiled library is sufficiently recent. On older platforms, the program will terminate in an
160unspecified unsuccessful manner, but the quality of diagnostics won't be great.
161
162However, users can also override that mechanism at two different levels. First, the mechanism can be
163overridden at compile time by defining the ``_LIBCPP_VERBOSE_ABORT(format, args...)`` variadic macro.
164When that macro is defined, it will be called with a format string as the first argument, followed by
165a series of arguments to format using printf-style formatting. Compile-time customization may be
166useful to get precise control over code generation, however it is also inconvenient to use in
167some cases. Indeed, compile-time customization of the verbose termination function requires that all
168translation units be compiled with a consistent definition for ``_LIBCPP_VERBOSE_ABORT`` to avoid ODR
169violations, which can add complexity in the build system of users.
170
171Otherwise, if compile-time customization is not necessary, link-time customization of the handler is also
172possible, similarly to how replacing ``operator new`` works. This mechanism trades off fine-grained control
173over the call site where the termination is initiated in exchange for better ergonomics. Link-time
174customization is done by simply defining the following function in exactly one translation unit of your
175program:
176
177.. code-block:: cpp
178
179  void __libcpp_verbose_abort(char const* format, ...)
180
181This mechanism is similar to how one can replace the default definition of ``operator new``
182and ``operator delete``. For example:
183
184.. code-block:: cpp
185
186  // In HelloWorldHandler.cpp
187  #include <version> // must include any libc++ header before defining the function (C compatibility headers excluded)
188
189  void std::__libcpp_verbose_abort(char const* format, ...) {
190    std::va_list list;
191    va_start(list, format);
192    std::vfprintf(stderr, format, list);
193    va_end(list);
194
195    std::abort();
196  }
197
198  // In HelloWorld.cpp
199  #include <vector>
200
201  int main() {
202    std::vector<int> v;
203    int& x = v[0]; // Your termination function will be called here if hardening is enabled.
204  }
205
206Also note that the verbose termination function should never return. Since assertions in libc++
207catch undefined behavior, your code will proceed with undefined behavior if your function is called
208and does return.
209
210Furthermore, exceptions should not be thrown from the function. Indeed, many functions in the
211library are ``noexcept``, and any exception thrown from the termination function will result
212in ``std::terminate`` being called.
213
214Libc++ Configuration Macros
215===========================
216
217Libc++ provides a number of configuration macros which can be used to enable
218or disable extended libc++ behavior, including enabling hardening or thread
219safety annotations.
220
221**_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS**:
222  This macro is used to enable -Wthread-safety annotations on libc++'s
223  ``std::mutex`` and ``std::lock_guard``. By default, these annotations are
224  disabled and must be manually enabled by the user.
225
226**_LIBCPP_HARDENING_MODE**:
227  This macro is used to choose the :ref:`hardening mode <using-hardening-modes>`.
228
229**_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS**:
230  This macro is used to disable all visibility annotations inside libc++.
231  Defining this macro and then building libc++ with hidden visibility gives a
232  build of libc++ which does not export any symbols, which can be useful when
233  building statically for inclusion into another library.
234
235**_LIBCPP_DISABLE_ADDITIONAL_DIAGNOSTICS**:
236  This macro disables the additional diagnostics generated by libc++ using the
237  `diagnose_if` attribute. These additional diagnostics include checks for:
238
239    * Giving `set`, `map`, `multiset`, `multimap` and their `unordered_`
240      counterparts a comparator which is not const callable.
241    * Giving an unordered associative container a hasher that is not const
242      callable.
243
244**_LIBCPP_NO_VCRUNTIME**:
245  Microsoft's C and C++ headers are fairly entangled, and some of their C++
246  headers are fairly hard to avoid. In particular, `vcruntime_new.h` gets pulled
247  in from a lot of other headers and provides definitions which clash with
248  libc++ headers, such as `nothrow_t` (note that `nothrow_t` is a struct, so
249  there's no way for libc++ to provide a compatible definition, since you can't
250  have multiple definitions).
251
252  By default, libc++ solves this problem by deferring to Microsoft's vcruntime
253  headers where needed. However, it may be undesirable to depend on vcruntime
254  headers, since they may not always be available in cross-compilation setups,
255  or they may clash with other headers. The `_LIBCPP_NO_VCRUNTIME` macro
256  prevents libc++ from depending on vcruntime headers. Consequently, it also
257  prevents libc++ headers from being interoperable with vcruntime headers (from
258  the aforementioned clashes), so users of this macro are promising to not
259  attempt to combine libc++ headers with the problematic vcruntime headers. This
260  macro also currently prevents certain `operator new`/`operator delete`
261  replacement scenarios from working, e.g. replacing `operator new` and
262  expecting a non-replaced `operator new[]` to call the replaced `operator new`.
263
264**_LIBCPP_DISABLE_NODISCARD_EXT**:
265  This macro disables library-extensions of ``[[nodiscard]]``.
266  See :ref:`Extended Applications of [[nodiscard]] <nodiscard extension>` for more information.
267
268**_LIBCPP_DISABLE_DEPRECATION_WARNINGS**:
269  This macro disables warnings when using deprecated components. For example,
270  using `std::auto_ptr` when compiling in C++11 mode will normally trigger a
271  warning saying that `std::auto_ptr` is deprecated. If the macro is defined,
272  no warning will be emitted. By default, this macro is not defined.
273
274C++17 Specific Configuration Macros
275-----------------------------------
276**_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES**:
277  This macro is used to re-enable all the features removed in C++17. The effect
278  is equivalent to manually defining each macro listed below.
279
280**_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR**:
281  This macro is used to re-enable `auto_ptr`.
282
283**_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS**:
284  This macro is used to re-enable the `binder1st`, `binder2nd`,
285  `pointer_to_unary_function`, `pointer_to_binary_function`, `mem_fun_t`,
286  `mem_fun1_t`, `mem_fun_ref_t`, `mem_fun1_ref_t`, `const_mem_fun_t`,
287  `const_mem_fun1_t`, `const_mem_fun_ref_t`, and `const_mem_fun1_ref_t`
288  class templates, and the `bind1st`, `bind2nd`, `mem_fun`, `mem_fun_ref`,
289  and `ptr_fun` functions.
290
291**_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE**:
292  This macro is used to re-enable the `random_shuffle` algorithm.
293
294**_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS**:
295  This macro is used to re-enable `set_unexpected`, `get_unexpected`, and
296  `unexpected`.
297
298C++20 Specific Configuration Macros
299-----------------------------------
300**_LIBCPP_ENABLE_CXX20_REMOVED_FEATURES**:
301  This macro is used to re-enable all the features removed in C++20. The effect
302  is equivalent to manually defining each macro listed below.
303
304**_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS**:
305  This macro is used to re-enable redundant members of `allocator<T>`,
306  including `pointer`, `reference`, `rebind`, `address`, `max_size`,
307  `construct`, `destroy`, and the two-argument overload of `allocate`.
308
309**_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_VOID_SPECIALIZATION**:
310  This macro is used to re-enable the library-provided specializations of
311  `allocator<void>` and `allocator<const void>`.
312  Use it in conjunction with `_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS`
313  to ensure that removed members of `allocator<void>` can be accessed.
314
315**_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS**:
316  This macro is used to re-enable the `argument_type`, `result_type`,
317  `first_argument_type`, and `second_argument_type` members of class
318  templates such as `plus`, `logical_not`, `hash`, and `owner_less`.
319
320**_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS**:
321  This macro is used to re-enable `not1`, `not2`, `unary_negate`,
322  and `binary_negate`.
323
324**_LIBCPP_ENABLE_CXX20_REMOVED_RAW_STORAGE_ITERATOR**:
325  This macro is used to re-enable `raw_storage_iterator`.
326
327**_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS**:
328  This macro is used to re-enable `is_literal_type`, `is_literal_type_v`,
329  `result_of` and `result_of_t`.
330
331
332C++26 Specific Configuration Macros
333-----------------------------------
334
335**_LIBCPP_ENABLE_CXX26_REMOVED_CODECVT**:
336  This macro is used to re-enable all named declarations in ``<codecvt>``.
337
338**_LIBCPP_ENABLE_CXX26_REMOVED_STRING_RESERVE**
339  This macro is used to re-enable the function
340  ``std::basic_string<...>::reserve()``.
341
342Libc++ Extensions
343=================
344
345This section documents various extensions provided by libc++, how they're
346provided, and any information regarding how to use them.
347
348.. _nodiscard extension:
349
350Extended applications of ``[[nodiscard]]``
351------------------------------------------
352
353The ``[[nodiscard]]`` attribute is intended to help users find bugs where
354function return values are ignored when they shouldn't be. After C++17 the
355C++ standard has started to declared such library functions as ``[[nodiscard]]``.
356However, this application is limited and applies only to dialects after C++17.
357Users who want help diagnosing misuses of STL functions may desire a more
358liberal application of ``[[nodiscard]]``.
359
360For this reason libc++ provides an extension that does just that! The
361extension is enabled by default and can be disabled by defining ``_LIBCPP_DISABLE_NODISCARD_EXT``.
362The extended applications of ``[[nodiscard]]`` takes two forms:
363
3641. Backporting ``[[nodiscard]]`` to entities declared as such by the
365   standard in newer dialects, but not in the present one.
366
3672. Extended applications of ``[[nodiscard]]``, at the library's discretion,
368   applied to entities never declared as such by the standard. You can find
369   all such applications by grepping for ``_LIBCPP_NODISCARD_EXT``.
370
371Extended integral type support
372------------------------------
373
374Several platforms support types that are not specified in the Standard, such as
375the 128-bit integral types ``__int128_t`` and ``__uint128_t``. As an extension,
376libc++ does a best-effort attempt to support these types like other integral
377types, by supporting them notably in:
378
379* ``<bits>``
380* ``<charconv>``
381* ``<functional>``
382* ``<type_traits>``
383* ``<format>``
384* ``<random>``
385
386Additional types supported in random distributions
387~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
388
389The `C++ Standard <http://eel.is/c++draft/rand#req.genl-1.5>`_ mentions that instantiating several random number
390distributions with types other than ``short``, ``int``, ``long``, ``long long``, and their unsigned versions is
391undefined. As an extension, libc++ supports instantiating ``binomial_distribution``, ``discrete_distribution``,
392``geometric_distribution``, ``negative_binomial_distribution``, ``poisson_distribution``, and ``uniform_int_distribution``
393with ``int8_t``, ``__int128_t`` and their unsigned versions.
394
395Extensions to ``<format>``
396--------------------------
397
398The exposition only type ``basic-format-string`` and its typedefs
399``format-string`` and ``wformat-string`` became ``basic_format_string``,
400``format_string``, and ``wformat_string`` in C++23. Libc++ makes these types
401available in C++20 as an extension.
402
403For padding Unicode strings the ``format`` library relies on the Unicode
404Standard. Libc++ retroactively updates the Unicode Standard in older C++
405versions. This allows the library to have better estimates for newly introduced
406Unicode code points, without requiring the user to use the latest C++ version
407in their code base.
408
409In C++26 formatting pointers gained a type ``P`` and allows to use
410zero-padding. These options have been retroactively applied to C++20.
411
412Extensions to the C++23 modules ``std`` and ``std.compat``
413----------------------------------------------------------
414
415Like other major implementations, libc++ provides C++23 modules ``std`` and
416``std.compat`` in C++20 as an extension"
417
418Constant-initialized std::string
419--------------------------------
420
421As an implementation-specific optimization, ``std::basic_string`` (``std::string``,
422``std::wstring``, etc.) may either store the string data directly in the object, or else store a
423pointer to heap-allocated memory, depending on the length of the string.
424
425As of C++20, the constructors are now declared ``constexpr``, which permits strings to be used
426during constant-evaluation time. In libc++, as in other common implementations, it is also possible
427to constant-initialize a string object (e.g. via declaring a variable with ``constinit`` or
428``constexpr``), but, only if the string is short enough to not require a heap allocation. Reliance
429upon this should be discouraged in portable code, as the allowed length differs based on the
430standard-library implementation and also based on whether the platform uses 32-bit or 64-bit
431pointers.
432
433.. code-block:: cpp
434
435  // Non-portable: 11-char string works on 64-bit libc++, but not on 32-bit.
436  constinit std::string x = "hello world";
437
438  // Prefer to use string_view, or remove constinit/constexpr from the variable definition:
439  constinit std::string_view x = "hello world";
440  std::string_view y = "hello world";
441
442.. _turning-off-asan:
443
444Turning off ASan annotation in containers
445-----------------------------------------
446
447``__asan_annotate_container_with_allocator`` is a customization point to allow users to disable
448`Address Sanitizer annotations for containers <https://github.com/google/sanitizers/wiki/AddressSanitizerContainerOverflow>`_ for specific allocators. This may be necessary for allocators that access allocated memory.
449This customization point exists only when ``_LIBCPP_HAS_ASAN_CONTAINER_ANNOTATIONS_FOR_ALL_ALLOCATORS`` Feature Test Macro is defined.
450
451For allocators not running destructors, it is also possible to `bulk-unpoison memory <https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning>`_ instead of disabling annotations altogether.
452
453The struct may be specialized for user-defined allocators. It is a `Cpp17UnaryTypeTrait <http://eel.is/c++draft/type.traits#meta.rqmts>`_ with a base characteristic of ``true_type`` if the container is allowed to use annotations and ``false_type`` otherwise.
454
455The annotations for a ``user_allocator`` can be disabled like this:
456
457.. code-block:: cpp
458
459  #ifdef _LIBCPP_HAS_ASAN_CONTAINER_ANNOTATIONS_FOR_ALL_ALLOCATORS
460  template <class T>
461  struct std::__asan_annotate_container_with_allocator<user_allocator<T>> : std::false_type {};
462  #endif
463
464Why may I want to turn it off?
465~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
466
467There are a few reasons why you may want to turn off annotations for an allocator.
468Unpoisoning may not be an option, if (for example) you are not maintaining the allocator.
469
470* You are using allocator, which does not call destructor during deallocation.
471* You are aware that memory allocated with an allocator may be accessed, even when unused by container.
472
473Platform specific behavior
474==========================
475
476Windows
477-------
478
479The ``stdout``, ``stderr``, and ``stdin`` file streams can be placed in
480Unicode mode by a suitable call to ``_setmode()``. When in this mode,
481the sequence of bytes read from, or written to, these streams is interpreted
482as a sequence of little-endian ``wchar_t`` elements. Thus, use of
483``std::cout``, ``std::cerr``, or ``std::cin`` with streams in Unicode mode
484will not behave as they usually do since bytes read or written won't be
485interpreted as individual ``char`` elements. However, ``std::wcout``,
486``std::wcerr``, and ``std::wcin`` will behave as expected.
487
488Wide character stream such as ``std::wcin`` or ``std::wcout`` imbued with a
489locale behave differently than they otherwise do. By default, wide character
490streams don't convert wide characters but input/output them as is. If a
491specific locale is imbued, the IO with the underlying stream happens with
492regular ``char`` elements, which are converted to/from wide characters
493according to the locale. Note that this doesn't behave as expected if the
494stream has been set in Unicode mode.
495