xref: /llvm-project/libcxx/docs/UserDocumentation.rst (revision 0a7e5e34569737447e9e3e08b5f87883300061e5)
1.. _user-documentation:
2
3==================
4User documentation
5==================
6
7.. contents::
8  :local:
9
10This page contains information about configuration knobs that can be used by
11users when they know libc++ is used by their toolchain, and how to use libc++
12when it is not the default library used by their toolchain. It is aimed at
13users of libc++: a separate page contains documentation aimed at vendors who
14build and ship libc++ as part of their toolchain.
15
16
17Using a different version of the C++ Standard
18=============================================
19
20Libc++ implements the various versions of the C++ Standard. Changing the version of
21the standard can be done by passing ``-std=c++XY`` to the compiler. Libc++ will
22automatically detect what Standard is being used and will provide functionality that
23matches that Standard in the library.
24
25.. code-block:: bash
26
27  $ clang++ -std=c++17 test.cpp
28
29Note that using ``-std=c++XY`` with a version of the Standard that has not been ratified
30yet is considered unstable. While we strive to maintain stability, libc++ may be forced to
31make breaking changes to features shipped in a Standard that hasn't been ratified yet. Use
32these versions of the Standard at your own risk.
33
34
35Using libc++ when it is not the system default
36==============================================
37
38Usually, libc++ is packaged and shipped by a vendor through some delivery vehicle
39(operating system distribution, SDK, toolchain, etc) and users don't need to do
40anything special in order to use the library.
41
42On systems where libc++ is provided but is not the default, Clang provides a flag
43called ``-stdlib=`` that can be used to decide which standard library is used.
44Using ``-stdlib=libc++`` will select libc++:
45
46.. code-block:: bash
47
48  $ clang++ -stdlib=libc++ test.cpp
49
50On systems where libc++ is the library in use by default such as macOS and FreeBSD,
51this flag is not required.
52
53
54Enabling experimental C++ Library features
55==========================================
56
57Libc++ provides implementations of some experimental features. Experimental features
58are either Technical Specifications (TSes) or official features that were voted to
59the Standard but whose implementation is not complete or stable yet in libc++. Those
60are disabled by default because they are neither API nor ABI stable. However, the
61``-fexperimental-library`` compiler flag can be defined to turn those features on.
62
63On compilers that do not support the ``-fexperimental-library`` flag (such as GCC),
64users can define the ``_LIBCPP_ENABLE_EXPERIMENTAL`` macro and manually link against
65the appropriate static library (usually shipped as ``libc++experimental.a``) to get
66access to experimental library features.
67
68The following features are currently considered experimental and are only provided
69when ``-fexperimental-library`` is passed:
70
71* The parallel algorithms library (``<execution>`` and the associated algorithms)
72* ``std::chrono::tzdb`` and related time zone functionality
73* ``<syncstream>``
74
75.. note::
76  Experimental libraries are experimental.
77    * The contents of the ``<experimental/...>`` headers and the associated static
78      library will not remain compatible between versions.
79    * No guarantees of API or ABI stability are provided.
80    * When the standardized version of an experimental feature is implemented,
81      the experimental feature is removed two releases after the non-experimental
82      version has shipped. The full policy is explained :ref:`here <experimental features>`.
83
84
85Libc++ Configuration Macros
86===========================
87
88Libc++ provides a number of configuration macros that can be used by developers to
89enable or disable extended libc++ behavior.
90
91.. warning::
92  Configuration macros that are not documented here are not intended to be customized
93  by developers and should not be used. In particular, some configuration macros are
94  only intended to be used by vendors and changing their value from the one provided
95  in your toolchain can lead to unexpected behavior.
96
97**_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS**:
98  This macro is used to enable -Wthread-safety annotations on libc++'s
99  ``std::mutex`` and ``std::lock_guard``. By default, these annotations are
100  disabled and must be manually enabled by the user.
101
102**_LIBCPP_HARDENING_MODE**:
103  This macro is used to choose the :ref:`hardening mode <using-hardening-modes>`.
104
105**_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS**:
106  This macro is used to disable all visibility annotations inside libc++.
107  Defining this macro and then building libc++ with hidden visibility gives a
108  build of libc++ which does not export any symbols, which can be useful when
109  building statically for inclusion into another library.
110
111**_LIBCPP_NO_VCRUNTIME**:
112  Microsoft's C and C++ headers are fairly entangled, and some of their C++
113  headers are fairly hard to avoid. In particular, `vcruntime_new.h` gets pulled
114  in from a lot of other headers and provides definitions which clash with
115  libc++ headers, such as `nothrow_t` (note that `nothrow_t` is a struct, so
116  there's no way for libc++ to provide a compatible definition, since you can't
117  have multiple definitions).
118
119  By default, libc++ solves this problem by deferring to Microsoft's vcruntime
120  headers where needed. However, it may be undesirable to depend on vcruntime
121  headers, since they may not always be available in cross-compilation setups,
122  or they may clash with other headers. The `_LIBCPP_NO_VCRUNTIME` macro
123  prevents libc++ from depending on vcruntime headers. Consequently, it also
124  prevents libc++ headers from being interoperable with vcruntime headers (from
125  the aforementioned clashes), so users of this macro are promising to not
126  attempt to combine libc++ headers with the problematic vcruntime headers. This
127  macro also currently prevents certain `operator new`/`operator delete`
128  replacement scenarios from working, e.g. replacing `operator new` and
129  expecting a non-replaced `operator new[]` to call the replaced `operator new`.
130
131**_LIBCPP_DISABLE_DEPRECATION_WARNINGS**:
132  This macro disables warnings when using deprecated components. For example,
133  using `std::auto_ptr` when compiling in C++11 mode will normally trigger a
134  warning saying that `std::auto_ptr` is deprecated. If the macro is defined,
135  no warning will be emitted. By default, this macro is not defined.
136
137**_LIBCPP_ENABLE_EXPERIMENTAL**:
138  This macro enables experimental features. This can be used on compilers that do
139  not support the ``-fexperimental-library`` flag. When used, users also need to
140  ensure that the appropriate experimental library (usually ``libc++experimental.a``)
141  is linked into their program.
142
143C++17 Specific Configuration Macros
144-----------------------------------
145**_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR**:
146  This macro is used to re-enable `auto_ptr`.
147
148**_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS**:
149  This macro is used to re-enable the `binder1st`, `binder2nd`,
150  `pointer_to_unary_function`, `pointer_to_binary_function`, `mem_fun_t`,
151  `mem_fun1_t`, `mem_fun_ref_t`, `mem_fun1_ref_t`, `const_mem_fun_t`,
152  `const_mem_fun1_t`, `const_mem_fun_ref_t`, and `const_mem_fun1_ref_t`
153  class templates, and the `bind1st`, `bind2nd`, `mem_fun`, `mem_fun_ref`,
154  and `ptr_fun` functions.
155
156**_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE**:
157  This macro is used to re-enable the `random_shuffle` algorithm.
158
159**_LIBCPP_ENABLE_CXX17_REMOVED_UNARY_BINARY_FUNCTION**:
160  This macro is used to re-enable `unary_function` and `binary_function`.
161
162**_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS**:
163  This macro is used to re-enable `set_unexpected`, `get_unexpected`, and
164  `unexpected`.
165
166C++20 Specific Configuration Macros
167-----------------------------------
168**_LIBCPP_ENABLE_CXX20_REMOVED_UNCAUGHT_EXCEPTION**:
169  This macro is used to re-enable `uncaught_exception`.
170
171**_LIBCPP_ENABLE_CXX20_REMOVED_SHARED_PTR_UNIQUE**:
172  This macro is used to re-enable the function
173  ``std::shared_ptr<...>::unique()``.
174
175**_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS**:
176  This macro is used to re-enable the `argument_type`, `result_type`,
177  `first_argument_type`, and `second_argument_type` members of class
178  templates such as `plus`, `logical_not`, `hash`, and `owner_less`.
179
180**_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS**:
181  This macro is used to re-enable `not1`, `not2`, `unary_negate`,
182  and `binary_negate`.
183
184**_LIBCPP_ENABLE_CXX20_REMOVED_RAW_STORAGE_ITERATOR**:
185  This macro is used to re-enable `raw_storage_iterator`.
186
187**_LIBCPP_ENABLE_CXX20_REMOVED_TEMPORARY_BUFFER**:
188  This macro is used to re-enable `get_temporary_buffer` and `return_temporary_buffer`.
189
190**_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS**:
191  This macro is used to re-enable `is_literal_type`, `is_literal_type_v`,
192  `result_of` and `result_of_t`.
193
194
195C++26 Specific Configuration Macros
196-----------------------------------
197
198**_LIBCPP_ENABLE_CXX26_REMOVED_CODECVT**:
199  This macro is used to re-enable all named declarations in ``<codecvt>``.
200
201**_LIBCPP_ENABLE_CXX26_REMOVED_STRING_RESERVE**:
202  This macro is used to re-enable the function
203  ``std::basic_string<...>::reserve()``.
204
205**_LIBCPP_ENABLE_CXX26_REMOVED_ALLOCATOR_MEMBERS**:
206  This macro is used to re-enable redundant member of ``allocator<T>::is_always_equal``.
207
208**_LIBCPP_ENABLE_CXX26_REMOVED_STRSTREAM**:
209  This macro is used to re-enable all named declarations in ``<strstream>``.
210
211**_LIBCPP_ENABLE_CXX26_REMOVED_WSTRING_CONVERT**:
212  This macro is used to re-enable the ``wstring_convert`` and ``wbuffer_convert``
213  in ``<locale>``.
214
215Libc++ Extensions
216=================
217
218This section documents various extensions provided by libc++, how they're
219provided, and any information regarding how to use them.
220
221Extended integral type support
222------------------------------
223
224Several platforms support types that are not specified in the Standard, such as
225the 128-bit integral types ``__int128_t`` and ``__uint128_t``. As an extension,
226libc++ does a best-effort attempt to support these types like other integral
227types, by supporting them notably in:
228
229* ``<bits>``
230* ``<charconv>``
231* ``<functional>``
232* ``<type_traits>``
233* ``<format>``
234* ``<random>``
235
236Additional types supported in random distributions
237~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
238
239The `C++ Standard <http://eel.is/c++draft/rand#req.genl-1.5>`_ mentions that instantiating several random number
240distributions with types other than ``short``, ``int``, ``long``, ``long long``, and their unsigned versions is
241undefined. As an extension, libc++ supports instantiating ``binomial_distribution``, ``discrete_distribution``,
242``geometric_distribution``, ``negative_binomial_distribution``, ``poisson_distribution``, and ``uniform_int_distribution``
243with ``int8_t``, ``__int128_t`` and their unsigned versions.
244
245Extensions to ``<format>``
246--------------------------
247
248The exposition only type ``basic-format-string`` and its typedefs
249``format-string`` and ``wformat-string`` became ``basic_format_string``,
250``format_string``, and ``wformat_string`` in C++23. Libc++ makes these types
251available in C++20 as an extension.
252
253For padding Unicode strings the ``format`` library relies on the Unicode
254Standard. Libc++ retroactively updates the Unicode Standard in older C++
255versions. This allows the library to have better estimates for newly introduced
256Unicode code points, without requiring the user to use the latest C++ version
257in their code base.
258
259In C++26 formatting pointers gained a type ``P`` and allows to use
260zero-padding. These options have been retroactively applied to C++20.
261
262Extensions to the C++23 modules ``std`` and ``std.compat``
263----------------------------------------------------------
264
265Like other major implementations, libc++ provides C++23 modules ``std`` and
266``std.compat`` in C++20 as an extension.
267
268Constant-initialized std::string
269--------------------------------
270
271As an implementation-specific optimization, ``std::basic_string`` (``std::string``,
272``std::wstring``, etc.) may either store the string data directly in the object, or else store a
273pointer to heap-allocated memory, depending on the length of the string.
274
275As of C++20, the constructors are now declared ``constexpr``, which permits strings to be used
276during constant-evaluation time. In libc++, as in other common implementations, it is also possible
277to constant-initialize a string object (e.g. via declaring a variable with ``constinit`` or
278``constexpr``), but, only if the string is short enough to not require a heap allocation. Reliance
279upon this should be discouraged in portable code, as the allowed length differs based on the
280standard-library implementation and also based on whether the platform uses 32-bit or 64-bit
281pointers.
282
283.. code-block:: cpp
284
285  // Non-portable: 11-char string works on 64-bit libc++, but not on 32-bit.
286  constinit std::string x = "hello world";
287
288  // Prefer to use string_view, or remove constinit/constexpr from the variable definition:
289  constinit std::string_view x = "hello world";
290  std::string_view y = "hello world";
291
292.. _turning-off-asan:
293
294Turning off ASan annotation in containers
295-----------------------------------------
296
297``__asan_annotate_container_with_allocator`` is a customization point to allow users to disable
298`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.
299This customization point exists only when ``_LIBCPP_HAS_ASAN_CONTAINER_ANNOTATIONS_FOR_ALL_ALLOCATORS`` Feature Test Macro is defined.
300
301For allocators not running destructors, it is also possible to `bulk-unpoison memory <https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning>`_ instead of disabling annotations altogether.
302
303The 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.
304
305The annotations for a ``user_allocator`` can be disabled like this:
306
307.. code-block:: cpp
308
309  #ifdef _LIBCPP_HAS_ASAN_CONTAINER_ANNOTATIONS_FOR_ALL_ALLOCATORS
310  template <class T>
311  struct std::__asan_annotate_container_with_allocator<user_allocator<T>> : std::false_type {};
312  #endif
313
314Why may I want to turn it off?
315~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
316
317There are a few reasons why you may want to turn off annotations for an allocator.
318Unpoisoning may not be an option, if (for example) you are not maintaining the allocator.
319
320* You are using allocator, which does not call destructor during deallocation.
321* You are aware that memory allocated with an allocator may be accessed, even when unused by container.
322
323Support for compiler extensions
324-------------------------------
325
326Clang, GCC and other compilers all provide their own set of language extensions. These extensions
327have often been developed without particular consideration for their interaction with the library,
328and as such, libc++ does not go out of its way to support them. The library may support specific
329compiler extensions which would then be documented explicitly, but the basic expectation should be
330that no special support is provided for arbitrary compiler extensions.
331
332Platform specific behavior
333==========================
334
335Windows
336-------
337
338The ``stdout``, ``stderr``, and ``stdin`` file streams can be placed in
339Unicode mode by a suitable call to ``_setmode()``. When in this mode,
340the sequence of bytes read from, or written to, these streams is interpreted
341as a sequence of little-endian ``wchar_t`` elements. Thus, use of
342``std::cout``, ``std::cerr``, or ``std::cin`` with streams in Unicode mode
343will not behave as they usually do since bytes read or written won't be
344interpreted as individual ``char`` elements. However, ``std::wcout``,
345``std::wcerr``, and ``std::wcin`` will behave as expected.
346
347Wide character stream such as ``std::wcin`` or ``std::wcout`` imbued with a
348locale behave differently than they otherwise do. By default, wide character
349streams don't convert wide characters but input/output them as is. If a
350specific locale is imbued, the IO with the underlying stream happens with
351regular ``char`` elements, which are converted to/from wide characters
352according to the locale. Note that this doesn't behave as expected if the
353stream has been set in Unicode mode.
354
355
356Third-party Integrations
357========================
358
359Libc++ provides integration with a few third-party tools.
360
361Debugging libc++ internals in LLDB
362----------------------------------
363
364LLDB hides the implementation details of libc++ by default.
365
366E.g., when setting a breakpoint in a comparator passed to ``std::sort``, the
367backtrace will read as
368
369.. code-block::
370
371  (lldb) thread backtrace
372  * thread #1, name = 'a.out', stop reason = breakpoint 3.1
373    * frame #0: 0x000055555555520e a.out`my_comparator(a=1, b=8) at test-std-sort.cpp:6:3
374      frame #7: 0x0000555555555615 a.out`void std::__1::sort[abi:ne200000]<std::__1::__wrap_iter<int*>, bool (*)(int, int)>(__first=(item = 8), __last=(item = 0), __comp=(a.out`my_less(int, int) at test-std-sort.cpp:5)) at sort.h:1003:3
375      frame #8: 0x000055555555531a a.out`main at test-std-sort.cpp:24:3
376
377Note how the caller of ``my_comparator`` is shown as ``std::sort``. Looking at
378the frame numbers, we can see that frames #1 until #6 were hidden. Those frames
379represent internal implementation details such as ``__sort4`` and similar
380utility functions.
381
382To also show those implementation details, use ``thread backtrace -u``.
383Alternatively, to disable those compact backtraces, use ``frame recognizer list``
384and ``frame recognizer disable`` on the "libc++ frame recognizer".
385
386Futhermore, stepping into libc++ functions is disabled by default. This is controlled via the
387setting ``target.process.thread.step-avoid-regexp`` which defaults to ``^std::`` and can be
388disabled using ``settings set target.process.thread.step-avoid-regexp ""``.
389
390GDB Pretty printers for libc++
391------------------------------
392
393GDB does not support pretty-printing of libc++ symbols by default. However, libc++ does
394provide pretty-printers itself. Those can be used as:
395
396.. code-block:: bash
397
398  $ gdb -ex "source <libcxx>/utils/gdb/libcxx/printers.py" \
399        -ex "python register_libcxx_printer_loader()" \
400        <args>
401
402
403.. _include-what-you-use:
404
405include-what-you-use (IWYU)
406---------------------------
407
408libc++ provides an IWYU `mapping file <https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/IWYUMappings.md>`_,
409which drastically improves the accuracy of the tool when using libc++. To use the mapping file with
410IWYU, you should run the tool like so:
411
412.. code-block:: bash
413
414  $ include-what-you-use -Xiwyu --mapping_file=/path/to/libcxx/include/libcxx.imp file.cpp
415
416If you would prefer to not use that flag, then you can replace ``/path/to/include-what-you-use/share/libcxx.imp``
417file with the libc++-provided ``libcxx.imp`` file.
418