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
37Using libc++experimental and ``<experimental/...>``
38===================================================
39
40Libc++ provides implementations of experimental technical specifications
41in a separate library, ``libc++experimental.a``. Users of ``<experimental/...>``
42headers may be required to link ``-lc++experimental``. Note that not all
43vendors ship ``libc++experimental.a``, and as a result, you may not be
44able to use those experimental features.
45
46.. code-block:: bash
47
48  $ clang++ test.cpp -lc++experimental
49
50.. warning::
51  Experimental libraries are Experimental.
52    * The contents of the ``<experimental/...>`` headers and ``libc++experimental.a``
53      library will not remain compatible between versions.
54    * No guarantees of API or ABI stability are provided.
55    * When the standardized version of an experimental feature is implemented,
56      the experimental feature is removed two releases after the non-experimental
57      version has shipped. The full policy is explained :ref:`here <experimental features>`.
58
59
60Using libc++ when it is not the system default
61==============================================
62
63On systems where libc++ is provided but is not the default, Clang provides a flag
64called ``-stdlib=`` that can be used to decide which standard library is used.
65Using ``-stdlib=libc++`` will select libc++:
66
67.. code-block:: bash
68
69  $ clang++ -stdlib=libc++ test.cpp
70
71On systems where libc++ is the library in use by default such as macOS and FreeBSD,
72this flag is not required.
73
74
75.. _alternate libcxx:
76
77Using a custom built libc++
78===========================
79
80Most compilers provide a way to disable the default behavior for finding the
81standard library and to override it with custom paths. With Clang, this can
82be done with:
83
84.. code-block:: bash
85
86  $ clang++ -nostdinc++ -nostdlib++           \
87            -isystem <install>/include/c++/v1 \
88            -L <install>/lib                  \
89            -Wl,-rpath,<install>/lib          \
90            -lc++                             \
91            test.cpp
92
93The option ``-Wl,-rpath,<install>/lib`` adds a runtime library search path,
94which causes the system's dynamic linker to look for libc++ in ``<install>/lib``
95whenever the program is loaded.
96
97GCC does not support the ``-nostdlib++`` flag, so one must use ``-nodefaultlibs``
98instead. Since that removes all the standard system libraries and not just libc++,
99the system libraries must be re-added manually. For example:
100
101.. code-block:: bash
102
103  $ g++ -nostdinc++ -nodefaultlibs           \
104        -isystem <install>/include/c++/v1    \
105        -L <install>/lib                     \
106        -Wl,-rpath,<install>/lib             \
107        -lc++ -lc++abi -lm -lc -lgcc_s -lgcc \
108        test.cpp
109
110
111GDB Pretty printers for libc++
112==============================
113
114GDB does not support pretty-printing of libc++ symbols by default. However, libc++ does
115provide pretty-printers itself. Those can be used as:
116
117.. code-block:: bash
118
119  $ gdb -ex "source <libcxx>/utils/gdb/libcxx/printers.py" \
120        -ex "python register_libcxx_printer_loader()" \
121        <args>
122
123
124.. _assertions-mode:
125
126Enabling the "safe libc++" mode
127===============================
128
129Libc++ contains a number of assertions whose goal is to catch undefined behavior in the
130library, usually caused by precondition violations. Those assertions do not aim to be
131exhaustive -- instead they aim to provide a good balance between safety and performance.
132In particular, these assertions do not change the complexity of algorithms. However, they
133might, in some cases, interfere with compiler optimizations.
134
135By default, these assertions are turned off. Vendors can decide to turn them on while building
136the compiled library by defining ``LIBCXX_ENABLE_ASSERTIONS=ON`` at CMake configuration time.
137When ``LIBCXX_ENABLE_ASSERTIONS`` is used, the compiled library will be built with assertions
138enabled, **and** user code will be built with assertions enabled by default. If
139``LIBCXX_ENABLE_ASSERTIONS=OFF`` at CMake configure time, the compiled library will not contain
140assertions and the default when building user code will be to have assertions disabled.
141As a user, you can consult your vendor to know whether assertions are enabled by default.
142
143Furthermore, independently of any vendor-selected default, users can always control whether
144assertions are enabled in their code by defining ``_LIBCPP_ENABLE_ASSERTIONS=0|1`` before
145including any libc++ header (we recommend passing ``-D_LIBCPP_ENABLE_ASSERTIONS=X`` to the
146compiler). Note that if the compiled library was built by the vendor without assertions,
147functions compiled inside the static or shared library won't have assertions enabled even
148if the user defines ``_LIBCPP_ENABLE_ASSERTIONS=1`` (the same is true for the inverse case
149where the static or shared library was compiled **with** assertions but the user tries to
150disable them). However, most of the code in libc++ is in the headers, so the user-selected
151value for ``_LIBCPP_ENABLE_ASSERTIONS`` (if any) will usually be respected.
152
153When an assertion fails, an assertion handler function is called. The library provides a default
154assertion handler that prints an error message and calls ``std::abort()``. Note that this assertion
155handler is provided by the static or shared library, so it is only available when deploying to a
156platform where the compiled library is sufficiently recent. However, users can also override that
157assertion handler with their own, which can be useful to provide custom behavior, or when deploying
158to older platforms where the default assertion handler isn't available.
159
160Replacing the default assertion handler is done by defining the following function:
161
162.. code-block:: cpp
163
164  void __libcpp_assertion_handler(char const* file, int line, char const* expression, char const* message)
165
166This mechanism is similar to how one can replace the default definition of ``operator new``
167and ``operator delete``. For example:
168
169.. code-block:: cpp
170
171  // In HelloWorldHandler.cpp
172  #include <version> // must include any libc++ header before defining the handler (C compatibility headers excluded)
173
174  void std::__libcpp_assertion_handler(char const* file, int line, char const* expression, char const* message) {
175    std::printf("Assertion %s failed at %s:%d, more info: %s", expression, file, line, message);
176    std::abort();
177  }
178
179  // In HelloWorld.cpp
180  #include <vector>
181
182  int main() {
183    std::vector<int> v;
184    int& x = v[0]; // Your assertion handler will be called here if _LIBCPP_ENABLE_ASSERTIONS=1
185  }
186
187Also note that the assertion handler should usually not return. Since the assertions in libc++
188catch undefined behavior, your code will proceed with undefined behavior if your assertion
189handler is called and does return.
190
191Furthermore, throwing an exception from the assertion handler is not recommended. Indeed, many
192functions in the library are ``noexcept``, and any exception thrown from the assertion handler
193will result in ``std::terminate`` being called.
194
195Back-deploying with a custom assertion handler
196----------------------------------------------
197When deploying to an older platform that does not provide a default assertion handler, the
198compiler will diagnose the usage of ``std::__libcpp_assertion_handler`` with an error. This
199is done to avoid the load-time error that would otherwise happen if the code was being deployed
200on the older system.
201
202If you are providing a custom assertion handler, this error is effectively a false positive.
203To let the library know that you are providing a custom assertion handler in back-deployment
204scenarios, you must define the ``_LIBCPP_AVAILABILITY_CUSTOM_ASSERTION_HANDLER_PROVIDED`` macro,
205and the library will assume that you are providing your own definition. If no definition is
206provided and the code is back-deployed to the older platform, it will fail to load when the
207dynamic linker fails to find a definition for ``std::__libcpp_assertion_handler``, so you
208should only remove the guard rails if you really mean it!
209
210Libc++ Configuration Macros
211===========================
212
213Libc++ provides a number of configuration macros which can be used to enable
214or disable extended libc++ behavior, including enabling "debug mode" or
215thread safety annotations.
216
217**_LIBCPP_DEBUG**:
218  See :ref:`using-debug-mode` for more information.
219
220**_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS**:
221  This macro is used to enable -Wthread-safety annotations on libc++'s
222  ``std::mutex`` and ``std::lock_guard``. By default, these annotations are
223  disabled and must be manually enabled by the user.
224
225**_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS**:
226  This macro is used to disable all visibility annotations inside libc++.
227  Defining this macro and then building libc++ with hidden visibility gives a
228  build of libc++ which does not export any symbols, which can be useful when
229  building statically for inclusion into another library.
230
231**_LIBCPP_DISABLE_EXTERN_TEMPLATE**:
232  This macro is used to disable extern template declarations in the libc++
233  headers. The intended use case is for clients who wish to use the libc++
234  headers without taking a dependency on the libc++ library itself.
235
236**_LIBCPP_DISABLE_ADDITIONAL_DIAGNOSTICS**:
237  This macro disables the additional diagnostics generated by libc++ using the
238  `diagnose_if` attribute. These additional diagnostics include checks for:
239
240    * Giving `set`, `map`, `multiset`, `multimap` and their `unordered_`
241      counterparts a comparator which is not const callable.
242    * Giving an unordered associative container a hasher that is not const
243      callable.
244
245**_LIBCPP_NO_VCRUNTIME**:
246  Microsoft's C and C++ headers are fairly entangled, and some of their C++
247  headers are fairly hard to avoid. In particular, `vcruntime_new.h` gets pulled
248  in from a lot of other headers and provides definitions which clash with
249  libc++ headers, such as `nothrow_t` (note that `nothrow_t` is a struct, so
250  there's no way for libc++ to provide a compatible definition, since you can't
251  have multiple definitions).
252
253  By default, libc++ solves this problem by deferring to Microsoft's vcruntime
254  headers where needed. However, it may be undesirable to depend on vcruntime
255  headers, since they may not always be available in cross-compilation setups,
256  or they may clash with other headers. The `_LIBCPP_NO_VCRUNTIME` macro
257  prevents libc++ from depending on vcruntime headers. Consequently, it also
258  prevents libc++ headers from being interoperable with vcruntime headers (from
259  the aforementioned clashes), so users of this macro are promising to not
260  attempt to combine libc++ headers with the problematic vcruntime headers. This
261  macro also currently prevents certain `operator new`/`operator delete`
262  replacement scenarios from working, e.g. replacing `operator new` and
263  expecting a non-replaced `operator new[]` to call the replaced `operator new`.
264
265**_LIBCPP_ENABLE_NODISCARD**:
266  Allow the library to add ``[[nodiscard]]`` attributes to entities not specified
267  as ``[[nodiscard]]`` by the current language dialect. This includes
268  backporting applications of ``[[nodiscard]]`` from newer dialects and
269  additional extended applications at the discretion of the library. All
270  additional applications of ``[[nodiscard]]`` are disabled by default.
271  See :ref:`Extended Applications of [[nodiscard]] <nodiscard extension>` for
272  more information.
273
274**_LIBCPP_DISABLE_NODISCARD_EXT**:
275  This macro prevents the library from applying ``[[nodiscard]]`` to entities
276  purely as an extension. See :ref:`Extended Applications of [[nodiscard]] <nodiscard extension>`
277  for more information.
278
279**_LIBCPP_DISABLE_DEPRECATION_WARNINGS**:
280  This macro disables warnings when using deprecated components. For example,
281  using `std::auto_ptr` when compiling in C++11 mode will normally trigger a
282  warning saying that `std::auto_ptr` is deprecated. If the macro is defined,
283  no warning will be emitted. By default, this macro is not defined.
284
285C++17 Specific Configuration Macros
286-----------------------------------
287**_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES**:
288  This macro is used to re-enable all the features removed in C++17. The effect
289  is equivalent to manually defining each macro listed below.
290
291**_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR**:
292  This macro is used to re-enable `auto_ptr`.
293
294**_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS**:
295  This macro is used to re-enable the `binder1st`, `binder2nd`,
296  `pointer_to_unary_function`, `pointer_to_binary_function`, `mem_fun_t`,
297  `mem_fun1_t`, `mem_fun_ref_t`, `mem_fun1_ref_t`, `const_mem_fun_t`,
298  `const_mem_fun1_t`, `const_mem_fun_ref_t`, and `const_mem_fun1_ref_t`
299  class templates, and the `bind1st`, `bind2nd`, `mem_fun`, `mem_fun_ref`,
300  and `ptr_fun` functions.
301
302**_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE**:
303  This macro is used to re-enable the `random_shuffle` algorithm.
304
305**_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS**:
306  This macro is used to re-enable `set_unexpected`, `get_unexpected`, and
307  `unexpected`.
308
309C++20 Specific Configuration Macros:
310------------------------------------
311**_LIBCPP_DISABLE_NODISCARD_AFTER_CXX17**:
312  This macro can be used to disable diagnostics emitted from functions marked
313  ``[[nodiscard]]`` in dialects after C++17.  See :ref:`Extended Applications of [[nodiscard]] <nodiscard extension>`
314  for more information.
315
316**_LIBCPP_ENABLE_CXX20_REMOVED_FEATURES**:
317  This macro is used to re-enable all the features removed in C++20. The effect
318  is equivalent to manually defining each macro listed below.
319
320**_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS**:
321  This macro is used to re-enable redundant members of `allocator<T>`,
322  including `pointer`, `reference`, `rebind`, `address`, `max_size`,
323  `construct`, `destroy`, and the two-argument overload of `allocate`.
324
325**_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS**:
326  This macro is used to re-enable the `argument_type`, `result_type`,
327  `first_argument_type`, and `second_argument_type` members of class
328  templates such as `plus`, `logical_not`, `hash`, and `owner_less`.
329
330**_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS**:
331  This macro is used to re-enable `not1`, `not2`, `unary_negate`,
332  and `binary_negate`.
333
334**_LIBCPP_ENABLE_CXX20_REMOVED_RAW_STORAGE_ITERATOR**:
335  This macro is used to re-enable `raw_storage_iterator`.
336
337**_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS**:
338  This macro is used to re-enable `is_literal_type`, `is_literal_type_v`,
339  `result_of` and `result_of_t`.
340
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 must be enabled by defining ``_LIBCPP_ENABLE_NODISCARD``. The extended
362applications 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.
369
370Users may also opt-out of additional applications ``[[nodiscard]]`` using
371additional macros.
372
373Applications of the first form, which backport ``[[nodiscard]]`` from a newer
374dialect, may be disabled using macros specific to the dialect in which it was
375added. For example, ``_LIBCPP_DISABLE_NODISCARD_AFTER_CXX17``.
376
377Applications of the second form, which are pure extensions, may be disabled
378by defining ``_LIBCPP_DISABLE_NODISCARD_EXT``.
379
380
381Entities declared with ``_LIBCPP_NODISCARD_EXT``
382~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383
384This section lists all extended applications of ``[[nodiscard]]`` to entities
385which no dialect declares as such (See the second form described above).
386
387* ``adjacent_find``
388* ``all_of``
389* ``any_of``
390* ``binary_search``
391* ``clamp``
392* ``count_if``
393* ``count``
394* ``equal_range``
395* ``equal``
396* ``find_end``
397* ``find_first_of``
398* ``find_if_not``
399* ``find_if``
400* ``find``
401* ``get_temporary_buffer``
402* ``includes``
403* ``is_heap_until``
404* ``is_heap``
405* ``is_partitioned``
406* ``is_permutation``
407* ``is_sorted_until``
408* ``is_sorted``
409* ``lexicographical_compare``
410* ``lower_bound``
411* ``max_element``
412* ``max``
413* ``min_element``
414* ``min``
415* ``minmax_element``
416* ``minmax``
417* ``mismatch``
418* ``none_of``
419* ``remove_if``
420* ``remove``
421* ``search_n``
422* ``search``
423* ``unique``
424* ``upper_bound``
425* ``lock_guard``'s constructors
426* ``as_const``
427* ``bit_cast``
428* ``forward``
429* ``move``
430* ``move_if_noexcept``
431* ``identity::operator()``
432* ``to_integer``
433* ``to_underlying``
434