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 54.. warning:: 55 Experimental libraries are experimental. 56 * The contents of the ``<experimental/...>`` headers and the associated static 57 library will not remain compatible between versions. 58 * No guarantees of API or ABI stability are provided. 59 * When the standardized version of an experimental feature is implemented, 60 the experimental feature is removed two releases after the non-experimental 61 version has shipped. The full policy is explained :ref:`here <experimental features>`. 62 63.. note:: 64 On compilers that do not support the ``-fexperimental-library`` flag, users can 65 define the ``_LIBCPP_ENABLE_EXPERIMENTAL`` macro and manually link against the 66 appropriate static library (usually shipped as ``libc++experimental.a``) to get 67 access to experimental library features. 68 69 70Using libc++ when it is not the system default 71============================================== 72 73On systems where libc++ is provided but is not the default, Clang provides a flag 74called ``-stdlib=`` that can be used to decide which standard library is used. 75Using ``-stdlib=libc++`` will select libc++: 76 77.. code-block:: bash 78 79 $ clang++ -stdlib=libc++ test.cpp 80 81On systems where libc++ is the library in use by default such as macOS and FreeBSD, 82this flag is not required. 83 84 85.. _alternate libcxx: 86 87Using a custom built libc++ 88=========================== 89 90Most compilers provide a way to disable the default behavior for finding the 91standard library and to override it with custom paths. With Clang, this can 92be done with: 93 94.. code-block:: bash 95 96 $ clang++ -nostdinc++ -nostdlib++ \ 97 -isystem <install>/include/c++/v1 \ 98 -L <install>/lib \ 99 -Wl,-rpath,<install>/lib \ 100 -lc++ \ 101 test.cpp 102 103The option ``-Wl,-rpath,<install>/lib`` adds a runtime library search path, 104which causes the system's dynamic linker to look for libc++ in ``<install>/lib`` 105whenever the program is loaded. 106 107GCC does not support the ``-nostdlib++`` flag, so one must use ``-nodefaultlibs`` 108instead. Since that removes all the standard system libraries and not just libc++, 109the system libraries must be re-added manually. For example: 110 111.. code-block:: bash 112 113 $ g++ -nostdinc++ -nodefaultlibs \ 114 -isystem <install>/include/c++/v1 \ 115 -L <install>/lib \ 116 -Wl,-rpath,<install>/lib \ 117 -lc++ -lc++abi -lm -lc -lgcc_s -lgcc \ 118 test.cpp 119 120 121GDB Pretty printers for libc++ 122============================== 123 124GDB does not support pretty-printing of libc++ symbols by default. However, libc++ does 125provide pretty-printers itself. Those can be used as: 126 127.. code-block:: bash 128 129 $ gdb -ex "source <libcxx>/utils/gdb/libcxx/printers.py" \ 130 -ex "python register_libcxx_printer_loader()" \ 131 <args> 132 133.. _include-what-you-use: 134 135include-what-you-use (IWYU) 136=========================== 137 138libc++ provides an IWYU `mapping file <https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/IWYUMappings.md>`_, 139which drastically improves the accuracy of the tool when using libc++. To use the mapping file with 140IWYU, you should run the tool like so: 141 142.. code-block:: bash 143 144 $ include-what-you-use -Xiwyu --mapping_file=/path/to/libcxx/include/libcxx.imp file.cpp 145 146If you would prefer to not use that flag, then you can replace ``/path/to/include-what-you-use/share/libcxx.imp`` 147file with the libc++-provided ``libcxx.imp`` file. 148 149Libc++ Configuration Macros 150=========================== 151 152Libc++ provides a number of configuration macros which can be used to enable 153or disable extended libc++ behavior, including enabling hardening or thread 154safety annotations. 155 156**_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS**: 157 This macro is used to enable -Wthread-safety annotations on libc++'s 158 ``std::mutex`` and ``std::lock_guard``. By default, these annotations are 159 disabled and must be manually enabled by the user. 160 161**_LIBCPP_HARDENING_MODE**: 162 This macro is used to choose the :ref:`hardening mode <using-hardening-modes>`. 163 164**_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS**: 165 This macro is used to disable all visibility annotations inside libc++. 166 Defining this macro and then building libc++ with hidden visibility gives a 167 build of libc++ which does not export any symbols, which can be useful when 168 building statically for inclusion into another library. 169 170**_LIBCPP_DISABLE_ADDITIONAL_DIAGNOSTICS**: 171 This macro disables the additional diagnostics generated by libc++ using the 172 `diagnose_if` attribute. These additional diagnostics include checks for: 173 174 * Giving `set`, `map`, `multiset`, `multimap` and their `unordered_` 175 counterparts a comparator which is not const callable. 176 * Giving an unordered associative container a hasher that is not const 177 callable. 178 179**_LIBCPP_NO_VCRUNTIME**: 180 Microsoft's C and C++ headers are fairly entangled, and some of their C++ 181 headers are fairly hard to avoid. In particular, `vcruntime_new.h` gets pulled 182 in from a lot of other headers and provides definitions which clash with 183 libc++ headers, such as `nothrow_t` (note that `nothrow_t` is a struct, so 184 there's no way for libc++ to provide a compatible definition, since you can't 185 have multiple definitions). 186 187 By default, libc++ solves this problem by deferring to Microsoft's vcruntime 188 headers where needed. However, it may be undesirable to depend on vcruntime 189 headers, since they may not always be available in cross-compilation setups, 190 or they may clash with other headers. The `_LIBCPP_NO_VCRUNTIME` macro 191 prevents libc++ from depending on vcruntime headers. Consequently, it also 192 prevents libc++ headers from being interoperable with vcruntime headers (from 193 the aforementioned clashes), so users of this macro are promising to not 194 attempt to combine libc++ headers with the problematic vcruntime headers. This 195 macro also currently prevents certain `operator new`/`operator delete` 196 replacement scenarios from working, e.g. replacing `operator new` and 197 expecting a non-replaced `operator new[]` to call the replaced `operator new`. 198 199**_LIBCPP_DISABLE_NODISCARD_EXT**: 200 This macro disables library-extensions of ``[[nodiscard]]``. 201 See :ref:`Extended Applications of [[nodiscard]] <nodiscard extension>` for more information. 202 203**_LIBCPP_DISABLE_DEPRECATION_WARNINGS**: 204 This macro disables warnings when using deprecated components. For example, 205 using `std::auto_ptr` when compiling in C++11 mode will normally trigger a 206 warning saying that `std::auto_ptr` is deprecated. If the macro is defined, 207 no warning will be emitted. By default, this macro is not defined. 208 209C++17 Specific Configuration Macros 210----------------------------------- 211**_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES**: 212 This macro is used to re-enable all the features removed in C++17. The effect 213 is equivalent to manually defining each macro listed below. 214 This macro is deprecated and will be removed in LLVM-19. Use the 215 individual macros listed below. 216 217**_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR**: 218 This macro is used to re-enable `auto_ptr`. 219 220**_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS**: 221 This macro is used to re-enable the `binder1st`, `binder2nd`, 222 `pointer_to_unary_function`, `pointer_to_binary_function`, `mem_fun_t`, 223 `mem_fun1_t`, `mem_fun_ref_t`, `mem_fun1_ref_t`, `const_mem_fun_t`, 224 `const_mem_fun1_t`, `const_mem_fun_ref_t`, and `const_mem_fun1_ref_t` 225 class templates, and the `bind1st`, `bind2nd`, `mem_fun`, `mem_fun_ref`, 226 and `ptr_fun` functions. 227 228**_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE**: 229 This macro is used to re-enable the `random_shuffle` algorithm. 230 231**_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS**: 232 This macro is used to re-enable `set_unexpected`, `get_unexpected`, and 233 `unexpected`. 234 235C++20 Specific Configuration Macros 236----------------------------------- 237**_LIBCPP_ENABLE_CXX20_REMOVED_SHARED_PTR_UNIQUE** 238 This macro is used to re-enable the function 239 ``std::shared_ptr<...>::unique()``. 240 241**_LIBCPP_ENABLE_CXX20_REMOVED_FEATURES**: 242 This macro is used to re-enable all the features removed in C++20. The effect 243 is equivalent to manually defining each macro listed below. 244 This macro is deprecated and will be removed in LLVM-19. Use the 245 individual macros listed below. 246 247**_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS**: 248 This macro is used to re-enable the `argument_type`, `result_type`, 249 `first_argument_type`, and `second_argument_type` members of class 250 templates such as `plus`, `logical_not`, `hash`, and `owner_less`. 251 252**_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS**: 253 This macro is used to re-enable `not1`, `not2`, `unary_negate`, 254 and `binary_negate`. 255 256**_LIBCPP_ENABLE_CXX20_REMOVED_RAW_STORAGE_ITERATOR**: 257 This macro is used to re-enable `raw_storage_iterator`. 258 259**_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS**: 260 This macro is used to re-enable `is_literal_type`, `is_literal_type_v`, 261 `result_of` and `result_of_t`. 262 263 264C++26 Specific Configuration Macros 265----------------------------------- 266 267**_LIBCPP_ENABLE_CXX26_REMOVED_CODECVT**: 268 This macro is used to re-enable all named declarations in ``<codecvt>``. 269 270**_LIBCPP_ENABLE_CXX26_REMOVED_STRING_RESERVE** 271 This macro is used to re-enable the function 272 ``std::basic_string<...>::reserve()``. 273 274**_LIBCPP_ENABLE_CXX26_REMOVED_ALLOCATOR_MEMBERS**: 275 This macro is used to re-enable redundant member of ``allocator<T>::is_always_equal`` 276 277Libc++ Extensions 278================= 279 280This section documents various extensions provided by libc++, how they're 281provided, and any information regarding how to use them. 282 283.. _nodiscard extension: 284 285Extended applications of ``[[nodiscard]]`` 286------------------------------------------ 287 288The ``[[nodiscard]]`` attribute is intended to help users find bugs where 289function return values are ignored when they shouldn't be. After C++17 the 290C++ standard has started to declared such library functions as ``[[nodiscard]]``. 291However, this application is limited and applies only to dialects after C++17. 292Users who want help diagnosing misuses of STL functions may desire a more 293liberal application of ``[[nodiscard]]``. 294 295For this reason libc++ provides an extension that does just that! The 296extension is enabled by default and can be disabled by defining ``_LIBCPP_DISABLE_NODISCARD_EXT``. 297The extended applications of ``[[nodiscard]]`` takes two forms: 298 2991. Backporting ``[[nodiscard]]`` to entities declared as such by the 300 standard in newer dialects, but not in the present one. 301 3022. Extended applications of ``[[nodiscard]]``, at the library's discretion, 303 applied to entities never declared as such by the standard. You can find 304 all such applications by grepping for ``_LIBCPP_NODISCARD_EXT``. 305 306Extended integral type support 307------------------------------ 308 309Several platforms support types that are not specified in the Standard, such as 310the 128-bit integral types ``__int128_t`` and ``__uint128_t``. As an extension, 311libc++ does a best-effort attempt to support these types like other integral 312types, by supporting them notably in: 313 314* ``<bits>`` 315* ``<charconv>`` 316* ``<functional>`` 317* ``<type_traits>`` 318* ``<format>`` 319* ``<random>`` 320 321Additional types supported in random distributions 322~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 323 324The `C++ Standard <http://eel.is/c++draft/rand#req.genl-1.5>`_ mentions that instantiating several random number 325distributions with types other than ``short``, ``int``, ``long``, ``long long``, and their unsigned versions is 326undefined. As an extension, libc++ supports instantiating ``binomial_distribution``, ``discrete_distribution``, 327``geometric_distribution``, ``negative_binomial_distribution``, ``poisson_distribution``, and ``uniform_int_distribution`` 328with ``int8_t``, ``__int128_t`` and their unsigned versions. 329 330Extensions to ``<format>`` 331-------------------------- 332 333The exposition only type ``basic-format-string`` and its typedefs 334``format-string`` and ``wformat-string`` became ``basic_format_string``, 335``format_string``, and ``wformat_string`` in C++23. Libc++ makes these types 336available in C++20 as an extension. 337 338For padding Unicode strings the ``format`` library relies on the Unicode 339Standard. Libc++ retroactively updates the Unicode Standard in older C++ 340versions. This allows the library to have better estimates for newly introduced 341Unicode code points, without requiring the user to use the latest C++ version 342in their code base. 343 344In C++26 formatting pointers gained a type ``P`` and allows to use 345zero-padding. These options have been retroactively applied to C++20. 346 347Extensions to the C++23 modules ``std`` and ``std.compat`` 348---------------------------------------------------------- 349 350Like other major implementations, libc++ provides C++23 modules ``std`` and 351``std.compat`` in C++20 as an extension" 352 353Constant-initialized std::string 354-------------------------------- 355 356As an implementation-specific optimization, ``std::basic_string`` (``std::string``, 357``std::wstring``, etc.) may either store the string data directly in the object, or else store a 358pointer to heap-allocated memory, depending on the length of the string. 359 360As of C++20, the constructors are now declared ``constexpr``, which permits strings to be used 361during constant-evaluation time. In libc++, as in other common implementations, it is also possible 362to constant-initialize a string object (e.g. via declaring a variable with ``constinit`` or 363``constexpr``), but, only if the string is short enough to not require a heap allocation. Reliance 364upon this should be discouraged in portable code, as the allowed length differs based on the 365standard-library implementation and also based on whether the platform uses 32-bit or 64-bit 366pointers. 367 368.. code-block:: cpp 369 370 // Non-portable: 11-char string works on 64-bit libc++, but not on 32-bit. 371 constinit std::string x = "hello world"; 372 373 // Prefer to use string_view, or remove constinit/constexpr from the variable definition: 374 constinit std::string_view x = "hello world"; 375 std::string_view y = "hello world"; 376 377.. _turning-off-asan: 378 379Turning off ASan annotation in containers 380----------------------------------------- 381 382``__asan_annotate_container_with_allocator`` is a customization point to allow users to disable 383`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. 384This customization point exists only when ``_LIBCPP_HAS_ASAN_CONTAINER_ANNOTATIONS_FOR_ALL_ALLOCATORS`` Feature Test Macro is defined. 385 386For allocators not running destructors, it is also possible to `bulk-unpoison memory <https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning>`_ instead of disabling annotations altogether. 387 388The 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. 389 390The annotations for a ``user_allocator`` can be disabled like this: 391 392.. code-block:: cpp 393 394 #ifdef _LIBCPP_HAS_ASAN_CONTAINER_ANNOTATIONS_FOR_ALL_ALLOCATORS 395 template <class T> 396 struct std::__asan_annotate_container_with_allocator<user_allocator<T>> : std::false_type {}; 397 #endif 398 399Why may I want to turn it off? 400~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 401 402There are a few reasons why you may want to turn off annotations for an allocator. 403Unpoisoning may not be an option, if (for example) you are not maintaining the allocator. 404 405* You are using allocator, which does not call destructor during deallocation. 406* You are aware that memory allocated with an allocator may be accessed, even when unused by container. 407 408Platform specific behavior 409========================== 410 411Windows 412------- 413 414The ``stdout``, ``stderr``, and ``stdin`` file streams can be placed in 415Unicode mode by a suitable call to ``_setmode()``. When in this mode, 416the sequence of bytes read from, or written to, these streams is interpreted 417as a sequence of little-endian ``wchar_t`` elements. Thus, use of 418``std::cout``, ``std::cerr``, or ``std::cin`` with streams in Unicode mode 419will not behave as they usually do since bytes read or written won't be 420interpreted as individual ``char`` elements. However, ``std::wcout``, 421``std::wcerr``, and ``std::wcin`` will behave as expected. 422 423Wide character stream such as ``std::wcin`` or ``std::wcout`` imbued with a 424locale behave differently than they otherwise do. By default, wide character 425streams don't convert wide characters but input/output them as is. If a 426specific locale is imbued, the IO with the underlying stream happens with 427regular ``char`` elements, which are converted to/from wide characters 428according to the locale. Note that this doesn't behave as expected if the 429stream has been set in Unicode mode. 430