1 ============================
2 Clang Compiler User's Manual
3 ============================
11 The Clang Compiler is an open-source compiler for the C family of
12 programming languages, aiming to be the best in class implementation of
13 these languages. Clang builds on the LLVM optimizer and code generator,
14 allowing it to provide high-quality optimization and code generation
15 support for many targets. For more general information, please see the
16 `Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
17 Site <http://llvm.org>`_.
19 This document describes important notes about using Clang as a compiler
20 for an end-user, documenting the supported features, command line
21 options, etc. If you are interested in using Clang to build a tool that
22 processes code, please see `the Clang Internals
23 Manual <InternalsManual.html>`_. If you are interested in the `Clang
24 Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
27 Clang is designed to support the C family of programming languages,
28 which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
29 :ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
30 language-specific information, please see the corresponding language
33 - :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
35 - :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
36 variants depending on base language.
37 - :ref:`C++ Language <cxx>`
38 - :ref:`Objective C++ Language <objcxx>`
40 In addition to these base languages and their dialects, Clang supports a
41 broad variety of language extensions, which are documented in the
42 corresponding language section. These extensions are provided to be
43 compatible with the GCC, Microsoft, and other popular compilers as well
44 as to improve functionality through Clang-specific features. The Clang
45 driver and language features are intentionally designed to be as
46 compatible with the GNU GCC compiler as reasonably possible, easing
47 migration from GCC to Clang. In most cases, code "just works".
49 In addition to language specific features, Clang has a variety of
50 features that depend on what CPU architecture or operating system is
51 being compiled for. Please see the :ref:`Target-Specific Features and
52 Limitations <target_features>` section for more details.
54 The rest of the introduction introduces some basic :ref:`compiler
55 terminology <terminology>` that is used throughout this manual and
56 contains a basic :ref:`introduction to using Clang <basicusage>` as a
57 command line compiler.
64 Front end, parser, backend, preprocessor, undefined behavior,
72 Intro to how to use a C compiler for newbies.
74 compile + link compile then link debug info enabling optimizations
75 picking a language to use, defaults to C99 by default. Autosenses based
76 on extension. using a makefile
81 This section is generally an index into other sections. It does not go
82 into depth on the ones that are covered by other sections. However, the
83 first part introduces the language selection and other high level
84 options like -c, -g, etc.
86 Options to Control Error and Warning Messages
87 ---------------------------------------------
89 **-Werror**: Turn warnings into errors.
91 **-Werror=foo**: Turn warning "foo" into an error.
93 **-Wno-error=foo**: Turn warning "foo" into an warning even if -Werror
96 **-Wfoo**: Enable warning "foo".
98 **-Wno-foo**: Disable warning "foo".
100 **-w**: Disable all warnings.
102 **-Weverything**: :ref:`Enable **all**
103 warnings. <diagnostics_enable_everything>`
105 **-pedantic**: Warn on language extensions.
107 **-pedantic-errors**: Error on language extensions.
109 **-Wsystem-headers**: Enable warnings from system headers.
111 **-ferror-limit=123**: Stop emitting diagnostics after 123 errors have
112 been produced. The default is 20, and the error limit can be disabled
113 with -ferror-limit=0.
115 **-ftemplate-backtrace-limit=123**: Only emit up to 123 template
116 instantiation notes within the template instantiation backtrace for a
117 single warning or error. The default is 10, and the limit can be
118 disabled with -ftemplate-backtrace-limit=0.
120 .. _cl_diag_formatting:
122 Formatting of Diagnostics
123 ^^^^^^^^^^^^^^^^^^^^^^^^^
125 Clang aims to produce beautiful diagnostics by default, particularly for
126 new users that first come to Clang. However, different people have
127 different preferences, and sometimes Clang is driven by another program
128 that wants to parse simple and consistent output, not a person. For
129 these cases, Clang provides a wide range of options to control the exact
130 output format of the diagnostics that it generates.
132 .. _opt_fshow-column:
134 **-f[no-]show-column**
135 Print column number in diagnostic.
137 This option, which defaults to on, controls whether or not Clang
138 prints the column number of a diagnostic. For example, when this is
139 enabled, Clang will print something like:
143 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
148 When this is disabled, Clang will print "test.c:28: warning..." with
151 The printed column numbers count bytes from the beginning of the
152 line; take care if your source contains multibyte characters.
154 .. _opt_fshow-source-location:
156 **-f[no-]show-source-location**
157 Print source file/line/column information in diagnostic.
159 This option, which defaults to on, controls whether or not Clang
160 prints the filename, line number and column number of a diagnostic.
161 For example, when this is enabled, Clang will print something like:
165 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
170 When this is disabled, Clang will not print the "test.c:28:8: "
173 .. _opt_fcaret-diagnostics:
175 **-f[no-]caret-diagnostics**
176 Print source line and ranges from source code in diagnostic.
177 This option, which defaults to on, controls whether or not Clang
178 prints the source line, source ranges, and caret when emitting a
179 diagnostic. For example, when this is enabled, Clang will print
184 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
189 **-f[no-]color-diagnostics**
190 This option, which defaults to on when a color-capable terminal is
191 detected, controls whether or not Clang prints diagnostics in color.
193 When this option is enabled, Clang will use colors to highlight
194 specific parts of the diagnostic, e.g.,
196 .. nasty hack to not lose our dignity
201 <b><span style="color:black">test.c:28:8: <span style="color:magenta">warning</span>: extra tokens at end of #endif directive [-Wextra-tokens]</span></b>
203 <span style="color:green">^</span>
204 <span style="color:green">//</span>
207 When this is disabled, Clang will just print:
211 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
216 **-fdiagnostics-format=clang/msvc/vi**
217 Changes diagnostic output format to better match IDEs and command line tools.
219 This option controls the output format of the filename, line number,
220 and column printed in diagnostic messages. The options, and their
221 affect on formatting a simple conversion diagnostic, follow:
226 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
231 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
236 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
238 **-f[no-]diagnostics-show-name**
239 Enable the display of the diagnostic name.
240 This option, which defaults to off, controls whether or not Clang
241 prints the associated name.
243 .. _opt_fdiagnostics-show-option:
245 **-f[no-]diagnostics-show-option**
246 Enable ``[-Woption]`` information in diagnostic line.
248 This option, which defaults to on, controls whether or not Clang
249 prints the associated :ref:`warning group <cl_diag_warning_groups>`
250 option name when outputting a warning diagnostic. For example, in
255 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
260 Passing **-fno-diagnostics-show-option** will prevent Clang from
261 printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
262 the diagnostic. This information tells you the flag needed to enable
263 or disable the diagnostic, either from the command line or through
264 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
266 .. _opt_fdiagnostics-show-category:
268 **-fdiagnostics-show-category=none/id/name**
269 Enable printing category information in diagnostic line.
271 This option, which defaults to "none", controls whether or not Clang
272 prints the category associated with a diagnostic when emitting it.
273 Each diagnostic may or many not have an associated category, if it
274 has one, it is listed in the diagnostic categorization field of the
275 diagnostic line (in the []'s).
277 For example, a format string warning will produce these three
278 renditions based on the setting of this option:
282 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
283 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
284 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
286 This category can be used by clients that want to group diagnostics
287 by category, so it should be a high level category. We want dozens
288 of these, not hundreds or thousands of them.
290 .. _opt_fdiagnostics-fixit-info:
292 **-f[no-]diagnostics-fixit-info**
293 Enable "FixIt" information in the diagnostics output.
295 This option, which defaults to on, controls whether or not Clang
296 prints the information on how to fix a specific diagnostic
297 underneath it when it knows. For example, in this output:
301 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
306 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
307 printing the "//" line at the end of the message. This information
308 is useful for users who may not understand what is wrong, but can be
309 confusing for machine parsing.
311 .. _opt_fdiagnostics-print-source-range-info:
313 **-f[no-]diagnostics-print-source-range-info**
314 Print machine parsable information about source ranges.
315 This option, which defaults to off, controls whether or not Clang
316 prints information about source ranges in a machine parsable format
317 after the file/line/column number information. The information is a
318 simple sequence of brace enclosed ranges, where each range lists the
319 start and end line/column locations. For example, in this output:
323 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
324 P = (P-42) + Gamma*4;
327 The {}'s are generated by -fdiagnostics-print-source-range-info.
329 The printed column numbers count bytes from the beginning of the
330 line; take care if your source contains multibyte characters.
332 **-fdiagnostics-parseable-fixits**
333 Print Fix-Its in a machine parseable form.
335 This option makes Clang print available Fix-Its in a machine
336 parseable format at the end of diagnostics. The following example
337 illustrates the format:
341 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
343 The range printed is a half-open range, so in this example the
344 characters at column 25 up to but not including column 29 on line 7
345 in t.cpp should be replaced with the string "Gamma". Either the
346 range or the replacement string may be empty (representing strict
347 insertions and strict erasures, respectively). Both the file name
348 and the insertion string escape backslash (as "\\\\"), tabs (as
349 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
350 non-printable characters (as octal "\\xxx").
352 The printed column numbers count bytes from the beginning of the
353 line; take care if your source contains multibyte characters.
356 Turns off elision in template type printing.
358 The default for template type printing is to elide as many template
359 arguments as possible, removing those which are the same in both
360 template types, leaving only the differences. Adding this flag will
361 print all the template arguments. If supported by the terminal,
362 highlighting will still appear on differing arguments.
368 t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
374 t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<int, map<float, int>>>' to 'vector<map<int, map<double, int>>>' for 1st argument;
376 **-fdiagnostics-show-template-tree**
377 Template type diffing prints a text tree.
379 For diffing large templated types, this option will cause Clang to
380 display the templates as an indented text tree, one argument per
381 line, with differences marked inline. This is compatible with
388 t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
390 -fdiagnostics-show-template-tree
394 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
402 .. _cl_diag_warning_groups:
404 Individual Warning Groups
405 ^^^^^^^^^^^^^^^^^^^^^^^^^
407 TODO: Generate this from tblgen. Define one anchor per warning group.
409 .. _opt_wextra-tokens:
412 Warn about excess tokens at the end of a preprocessor directive.
414 This option, which defaults to on, enables warnings about extra
415 tokens at the end of preprocessor directives. For example:
419 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
423 These extra tokens are not strictly conforming, and are usually best
424 handled by commenting them out.
426 **-Wambiguous-member-template**
427 Warn about unqualified uses of a member template whose name resolves to
428 another template at the location of the use.
430 This option, which defaults to on, enables a warning in the
435 template<typename T> struct set{};
436 template<typename T> struct trait { typedef const T& type; };
438 template<typename T> void set(typename trait<T>::type value) {}
445 C++ [basic.lookup.classref] requires this to be an error, but,
446 because it's hard to work around, Clang downgrades it to a warning
449 **-Wbind-to-temporary-copy**
450 Warn about an unusable copy constructor when binding a reference to a
453 This option, which defaults to on, enables warnings about binding a
454 reference to a temporary when the temporary doesn't have a usable
455 copy constructor. For example:
462 NonCopyable(const NonCopyable&);
464 void foo(const NonCopyable&);
466 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
471 struct NonCopyable2 {
473 NonCopyable2(NonCopyable2&);
475 void foo(const NonCopyable2&);
477 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
480 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
481 whose instantiation produces a compile error, that error will still
482 be a hard error in C++98 mode even if this warning is turned off.
484 Options to Control Clang Crash Diagnostics
485 ------------------------------------------
487 As unbelievable as it may sound, Clang does crash from time to time.
488 Generally, this only occurs to those living on the `bleeding
489 edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
490 lengths to assist you in filing a bug report. Specifically, Clang
491 generates preprocessed source file(s) and associated run script(s) upon
492 a crash. These files should be attached to a bug report to ease
493 reproducibility of the failure. Below are the command line options to
494 control the crash diagnostics.
496 **-fno-crash-diagnostics**: Disable auto-generation of preprocessed
497 source files during a clang crash.
499 The -fno-crash-diagnostics flag can be helpful for speeding the process
500 of generating a delta reduced test case.
502 Language and Target-Independent Features
503 ========================================
505 Controlling Errors and Warnings
506 -------------------------------
508 Clang provides a number of ways to control which code constructs cause
509 it to emit errors and warning messages, and how they are displayed to
512 Controlling How Clang Displays Diagnostics
513 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
515 When Clang emits a diagnostic, it includes rich information in the
516 output, and gives you fine-grain control over which information is
517 printed. Clang has the ability to print this information, and these are
518 the options that control it:
520 #. A file/line/column indicator that shows exactly where the diagnostic
521 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
522 :ref:`-fshow-source-location <opt_fshow-source-location>`].
523 #. A categorization of the diagnostic as a note, warning, error, or
525 #. A text string that describes what the problem is.
526 #. An option that indicates how to control the diagnostic (for
527 diagnostics that support it)
528 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
529 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
530 for clients that want to group diagnostics by class (for diagnostics
532 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
533 #. The line of source code that the issue occurs on, along with a caret
534 and ranges that indicate the important locations
535 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
536 #. "FixIt" information, which is a concise explanation of how to fix the
537 problem (when Clang is certain it knows)
538 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
539 #. A machine-parsable representation of the ranges involved (off by
541 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
543 For more information please see :ref:`Formatting of
544 Diagnostics <cl_diag_formatting>`.
549 All diagnostics are mapped into one of these 5 classes:
557 .. _diagnostics_categories:
559 Diagnostic Categories
560 ^^^^^^^^^^^^^^^^^^^^^
562 Though not shown by default, diagnostics may each be associated with a
563 high-level category. This category is intended to make it possible to
564 triage builds that produce a large number of errors or warnings in a
567 Categories are not shown by default, but they can be turned on with the
568 :ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
569 When set to "``name``", the category is printed textually in the
570 diagnostic output. When it is set to "``id``", a category number is
571 printed. The mapping of category names to category id's can be obtained
572 by running '``clang --print-diagnostic-categories``'.
574 Controlling Diagnostics via Command Line Flags
575 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
577 TODO: -W flags, -pedantic, etc
579 .. _pragma_gcc_diagnostic:
581 Controlling Diagnostics via Pragmas
582 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
584 Clang can also control what diagnostics are enabled through the use of
585 pragmas in the source code. This is useful for turning off specific
586 warnings in a section of source code. Clang supports GCC's pragma for
587 compatibility with existing source code, as well as several extensions.
589 The pragma may control any warning that can be used from the command
590 line. Warnings may be set to ignored, warning, error, or fatal. The
591 following example code will tell Clang or GCC to ignore the -Wall
596 #pragma GCC diagnostic ignored "-Wall"
598 In addition to all of the functionality provided by GCC's pragma, Clang
599 also allows you to push and pop the current warning state. This is
600 particularly useful when writing a header file that will be compiled by
601 other people, because you don't know what warning flags they build with.
603 In the below example -Wmultichar is ignored for only a single line of
604 code, after which the diagnostics return to whatever state had
609 #pragma clang diagnostic push
610 #pragma clang diagnostic ignored "-Wmultichar"
612 char b = 'df'; // no warning.
614 #pragma clang diagnostic pop
616 The push and pop pragmas will save and restore the full diagnostic state
617 of the compiler, regardless of how it was set. That means that it is
618 possible to use push and pop around GCC compatible diagnostics and Clang
619 will push and pop them appropriately, while GCC will ignore the pushes
620 and pops as unknown pragmas. It should be noted that while Clang
621 supports the GCC pragma, Clang and GCC do not support the exact same set
622 of warnings, so even when using GCC compatible #pragmas there is no
623 guarantee that they will have identical behaviour on both compilers.
625 Controlling Diagnostics in System Headers
626 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
628 Warnings are suppressed when they occur in system headers. By default,
629 an included file is treated as a system header if it is found in an
630 include path specified by ``-isystem``, but this can be overridden in
633 The ``system_header`` pragma can be used to mark the current file as
634 being a system header. No warnings will be produced from the location of
635 the pragma onwards within the same file.
639 char a = 'xy'; // warning
641 #pragma clang system_header
643 char b = 'ab'; // no warning
645 The ``-isystem-prefix`` and ``-ino-system-prefix`` command-line
646 arguments can be used to override whether subsets of an include path are
647 treated as system headers. When the name in a ``#include`` directive is
648 found within a header search path and starts with a system prefix, the
649 header is treated as a system header. The last prefix on the
650 command-line which matches the specified header name takes precedence.
655 clang -Ifoo -isystem bar -isystem-prefix x/ -ino-system-prefix x/y/
657 Here, ``#include "x/a.h"`` is treated as including a system header, even
658 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
659 as not including a system header, even if the header is found in
662 A ``#include`` directive which finds a file relative to the current
663 directory is treated as including a system header if the including file
664 is treated as a system header.
666 .. _diagnostics_enable_everything:
668 Enabling All Warnings
669 ^^^^^^^^^^^^^^^^^^^^^
671 In addition to the traditional ``-W`` flags, one can enable **all**
672 warnings by passing ``-Weverything``. This works as expected with
673 ``-Werror``, and also includes the warnings from ``-pedantic``.
675 Note that when combined with ``-w`` (which disables all warnings), that
678 Controlling Static Analyzer Diagnostics
679 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
681 While not strictly part of the compiler, the diagnostics from Clang's
682 `static analyzer <http://clang-analyzer.llvm.org>`_ can also be
683 influenced by the user via changes to the source code. See the available
684 `annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
686 page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
692 `Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
693 are a general approach employed by many compilers to reduce compilation
694 time. The underlying motivation of the approach is that it is common for
695 the same (and often large) header files to be included by multiple
696 source files. Consequently, compile times can often be greatly improved
697 by caching some of the (redundant) work done by a compiler to process
698 headers. Precompiled header files, which represent one of many ways to
699 implement this optimization, are literally files that represent an
700 on-disk cache that contains the vital information necessary to reduce
701 some of the work needed to process a corresponding header file. While
702 details of precompiled headers vary between compilers, precompiled
703 headers have been shown to be highly effective at speeding up program
704 compilation on systems with very large system headers (e.g., Mac OS/X).
706 Generating a PCH File
707 ^^^^^^^^^^^^^^^^^^^^^
709 To generate a PCH file using Clang, one invokes Clang with the
710 **``-x <language>-header``** option. This mirrors the interface in GCC
711 for generating PCH files:
715 $ gcc -x c-header test.h -o test.h.gch
716 $ clang -x c-header test.h -o test.h.pch
721 A PCH file can then be used as a prefix header when a **``-include``**
722 option is passed to ``clang``:
726 $ clang -include test.h test.c -o test
728 The ``clang`` driver will first check if a PCH file for ``test.h`` is
729 available; if so, the contents of ``test.h`` (and the files it includes)
730 will be processed from the PCH file. Otherwise, Clang falls back to
731 directly processing the content of ``test.h``. This mirrors the behavior
735 Clang does *not* automatically use PCH files for headers that are
736 directly included within a source file. For example:
740 $ clang -x c-header test.h -o test.h.pch
743 $ clang test.c -o test
745 In this example, ``clang`` will not automatically use the PCH file for
746 ``test.h`` since ``test.h`` was included directly in the source file and
747 not specified on the command line using ``-include``.
749 Relocatable PCH Files
750 ^^^^^^^^^^^^^^^^^^^^^
752 It is sometimes necessary to build a precompiled header from headers
753 that are not yet in their final, installed locations. For example, one
754 might build a precompiled header within the build tree that is then
755 meant to be installed alongside the headers. Clang permits the creation
756 of "relocatable" precompiled headers, which are built with a given path
757 (into the build directory) and can later be used from an installed
760 To build a relocatable precompiled header, place your headers into a
761 subdirectory whose structure mimics the installed location. For example,
762 if you want to build a precompiled header for the header ``mylib.h``
763 that will be installed into ``/usr/include``, create a subdirectory
764 ``build/usr/include`` and place the header ``mylib.h`` into that
765 subdirectory. If ``mylib.h`` depends on other headers, then they can be
766 stored within ``build/usr/include`` in a way that mimics the installed
769 Building a relocatable precompiled header requires two additional
770 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
771 the resulting PCH file should be relocatable. Second, pass
772 ``-isysroot /path/to/build``, which makes all includes for your library
773 relative to the build directory. For example:
777 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
779 When loading the relocatable PCH file, the various headers used in the
780 PCH file are found from the system header root. For example, ``mylib.h``
781 can be found in ``/usr/include/mylib.h``. If the headers are installed
782 in some other system root, the ``-isysroot`` option can be used provide
783 a different system root from which the headers will be based. For
784 example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
785 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
787 Relocatable precompiled headers are intended to be used in a limited
788 number of cases where the compilation environment is tightly controlled
789 and the precompiled header cannot be generated after headers have been
790 installed. Relocatable precompiled headers also have some performance
791 impact, because the difference in location between the header locations
792 at PCH build time vs. at the time of PCH use requires one of the PCH
793 optimizations, ``stat()`` caching, to be disabled. However, this change
794 is only likely to affect PCH files that reference a large number of
797 Controlling Code Generation
798 ---------------------------
800 Clang provides a number of ways to control code generation. The options
803 **-fsanitize=check1,check2**
804 Turn on runtime checks for various forms of undefined or suspicious
807 This option controls whether Clang adds runtime checks for various
808 forms of undefined or suspicious behavior, and is disabled by
809 default. If a check fails, a diagnostic message is produced at
810 runtime explaining the problem. The main checks are:
812 .. _opt_fsanitize_address:
814 - ``-fsanitize=address``:
815 :doc:`AddressSanitizer`, a memory error
817 - ``-fsanitize=address-full``: AddressSanitizer with all the
818 experimental features listed below.
819 - ``-fsanitize=integer``: Enables checks for undefined or
820 suspicious integer behavior.
821 - ``-fsanitize=thread``: :doc:`ThreadSanitizer`,
822 an *experimental* data race detector. Not ready for widespread
825 .. _opt_fsanitize_undefined:
827 - ``-fsanitize=undefined``: Fast and compatible undefined behavior
828 checker. Enables the undefined behavior checks that have small
829 runtime cost and no impact on address space layout or ABI. This
830 includes all of the checks listed below other than
831 ``unsigned-integer-overflow``.
833 The following more fine-grained checks are also available:
835 - ``-fsanitize=alignment``: Use of a misaligned pointer or creation
836 of a misaligned reference.
837 - ``-fsanitize=bounds``: Out of bounds array indexing, in cases
838 where the array bound can be statically determined.
839 - ``-fsanitize=float-cast-overflow``: Conversion to, from, or
840 between floating-point types which would overflow the
842 - ``-fsanitize=float-divide-by-zero``: Floating point division by
844 - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
845 - ``-fsanitize=null``: Use of a null pointer or creation of a null
847 - ``-fsanitize=object-size``: An attempt to use bytes which the
848 optimizer can determine are not part of the object being
849 accessed. The sizes of objects are determined using
850 ``__builtin_object_size``, and consequently may be able to detect
851 more problems at higher optimization levels.
852 - ``-fsanitize=return``: In C++, reaching the end of a
853 value-returning function without returning a value.
854 - ``-fsanitize=shift``: Shift operators where the amount shifted is
855 greater or equal to the promoted bit-width of the left hand side
856 or less than zero, or where the left hand side is negative. For a
857 signed left shift, also checks for signed overflow in C, and for
858 unsigned overflow in C++.
859 - ``-fsanitize=signed-integer-overflow``: Signed integer overflow,
860 including all the checks added by ``-ftrapv``, and checking for
861 overflow in signed division (``INT_MIN / -1``).
862 - ``-fsanitize=unreachable``: If control flow reaches
863 ``__builtin_unreachable``.
864 - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer
866 - ``-fsanitize=vla-bound``: A variable-length array whose bound
867 does not evaluate to a positive value.
868 - ``-fsanitize=vptr``: Use of an object whose vptr indicates that
869 it is of the wrong dynamic type, or that its lifetime has not
870 begun or has ended. Incompatible with ``-fno-rtti``.
872 Experimental features of AddressSanitizer (not ready for widespread
873 use, require explicit ``-fsanitize=address``):
875 - ``-fsanitize=init-order``: Check for dynamic initialization order
877 - ``-fsanitize=use-after-return``: Check for use-after-return
878 errors (accessing local variable after the function exit).
879 - ``-fsanitize=use-after-scope``: Check for use-after-scope errors
880 (accesing local variable after it went out of scope).
882 The ``-fsanitize=`` argument must also be provided when linking, in
883 order to link to the appropriate runtime library. It is not possible
884 to combine the ``-fsanitize=address`` and ``-fsanitize=thread``
885 checkers in the same program.
886 **-f[no-]address-sanitizer**
887 Deprecated synonym for :ref:`-f[no-]sanitize=address
888 <opt_fsanitize_address>`.
889 **-f[no-]thread-sanitizer**
890 Deprecated synonym for :ref:`-f[no-]sanitize=thread
891 <opt_fsanitize_address>`.
892 **-fcatch-undefined-behavior**
893 Deprecated synonym for :ref:`-fsanitize=undefined
894 <opt_fsanitize_undefined>`.
895 **-fno-assume-sane-operator-new**
896 Don't assume that the C++'s new operator is sane.
898 This option tells the compiler to do not assume that C++'s global
899 new operator will always return a pointer that does not alias any
900 other pointer when the function returns.
902 **-ftrap-function=[name]**
903 Instruct code generator to emit a function call to the specified
904 function name for ``__builtin_trap()``.
906 LLVM code generator translates ``__builtin_trap()`` to a trap
907 instruction if it is supported by the target ISA. Otherwise, the
908 builtin is translated into a call to ``abort``. If this option is
909 set, then the code generator will always lower the builtin to a call
910 to the specified function regardless of whether the target ISA has a
911 trap instruction. This option is useful for environments (e.g.
912 deeply embedded) where a trap cannot be properly handled, or when
913 some custom behavior is desired.
915 **-ftls-model=[model]**
916 Select which TLS model to use.
918 Valid values are: ``global-dynamic``, ``local-dynamic``,
919 ``initial-exec`` and ``local-exec``. The default value is
920 ``global-dynamic``. The compiler may use a different model if the
921 selected model is not supported by the target, or if a more
922 efficient model can be used. The TLS model can be overridden per
923 variable using the ``tls_model`` attribute.
925 Controlling Size of Debug Information
926 -------------------------------------
928 Debug info kind generated by Clang can be set by one of the flags listed
929 below. If multiple flags are present, the last one is used.
931 **-g0**: Don't generate any debug info (default).
933 **-gline-tables-only**: Generate line number tables only.
935 This kind of debug info allows to obtain stack traces with function
936 names, file names and line numbers (by such tools as gdb or addr2line).
937 It doesn't contain any other data (e.g. description of local variables
938 or function parameters).
940 **-g**: Generate complete debug info.
947 The support for standard C in clang is feature-complete except for the
948 C99 floating-point pragmas.
950 Extensions supported by clang
951 -----------------------------
953 See `clang language extensions <LanguageExtensions.html>`_.
955 Differences between various standard modes
956 ------------------------------------------
958 clang supports the -std option, which changes what language mode clang
959 uses. The supported modes for C are c89, gnu89, c94, c99, gnu99 and
960 various aliases for those modes. If no -std option is specified, clang
961 defaults to gnu99 mode.
963 Differences between all ``c*`` and ``gnu*`` modes:
965 - ``c*`` modes define "``__STRICT_ANSI__``".
966 - Target-specific defines not prefixed by underscores, like "linux",
967 are defined in ``gnu*`` modes.
968 - Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
969 the -trigraphs option.
970 - The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
971 the variants "``__asm__``" and "``__typeof__``" are recognized in all
973 - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
974 on some platforms; it can be enabled in any mode with the "-fblocks"
976 - Arrays that are VLA's according to the standard, but which can be
977 constant folded by the frontend are treated as fixed size arrays.
978 This occurs for things like "int X[(1, 2)];", which is technically a
979 VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
981 Differences between ``*89`` and ``*99`` modes:
983 - The ``*99`` modes default to implementing "inline" as specified in C99,
984 while the ``*89`` modes implement the GNU version. This can be
985 overridden for individual functions with the ``__gnu_inline__``
987 - Digraphs are not recognized in c89 mode.
988 - The scope of names defined inside a "for", "if", "switch", "while",
989 or "do" statement is different. (example: "``if ((struct x {int
991 - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
992 - "inline" is not recognized as a keyword in c89 mode.
993 - "restrict" is not recognized as a keyword in ``*89`` modes.
994 - Commas are allowed in integer constant expressions in ``*99`` modes.
995 - Arrays which are not lvalues are not implicitly promoted to pointers
997 - Some warnings are different.
999 c94 mode is identical to c89 mode except that digraphs are enabled in
1000 c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1002 GCC extensions not implemented yet
1003 ----------------------------------
1005 clang tries to be compatible with gcc as much as possible, but some gcc
1006 extensions are not implemented yet:
1008 - clang does not support #pragma weak (`bug
1009 3679 <http://llvm.org/bugs/show_bug.cgi?id=3679>`_). Due to the uses
1010 described in the bug, this is likely to be implemented at some point,
1012 - clang does not support decimal floating point types (``_Decimal32`` and
1013 friends) or fixed-point types (``_Fract`` and friends); nobody has
1014 expressed interest in these features yet, so it's hard to say when
1015 they will be implemented.
1016 - clang does not support nested functions; this is a complex feature
1017 which is infrequently used, so it is unlikely to be implemented
1018 anytime soon. In C++11 it can be emulated by assigning lambda
1019 functions to local variables, e.g:
1023 auto const local_function = [&](int parameter) {
1029 - clang does not support global register variables; this is unlikely to
1030 be implemented soon because it requires additional LLVM backend
1032 - clang does not support static initialization of flexible array
1033 members. This appears to be a rarely used extension, but could be
1034 implemented pending user demand.
1035 - clang does not support
1036 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
1037 used rarely, but in some potentially interesting places, like the
1038 glibc headers, so it may be implemented pending user demand. Note
1039 that because clang pretends to be like GCC 4.2, and this extension
1040 was introduced in 4.3, the glibc headers will not try to use this
1041 extension with clang at the moment.
1042 - clang does not support the gcc extension for forward-declaring
1043 function parameters; this has not shown up in any real-world code
1044 yet, though, so it might never be implemented.
1046 This is not a complete list; if you find an unsupported extension
1047 missing from this list, please send an e-mail to cfe-dev. This list
1048 currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1049 list does not include bugs in mostly-implemented features; please see
1051 tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
1052 for known existing bugs (FIXME: Is there a section for bug-reporting
1053 guidelines somewhere?).
1055 Intentionally unsupported GCC extensions
1056 ----------------------------------------
1058 - clang does not support the gcc extension that allows variable-length
1059 arrays in structures. This is for a few reasons: one, it is tricky to
1060 implement, two, the extension is completely undocumented, and three,
1061 the extension appears to be rarely used. Note that clang *does*
1062 support flexible array members (arrays with a zero or unspecified
1063 size at the end of a structure).
1064 - clang does not have an equivalent to gcc's "fold"; this means that
1065 clang doesn't accept some constructs gcc might accept in contexts
1066 where a constant expression is required, like "x-x" where x is a
1068 - clang does not support ``__builtin_apply`` and friends; this extension
1069 is extremely obscure and difficult to implement reliably.
1073 Microsoft extensions
1074 --------------------
1076 clang has some experimental support for extensions from Microsoft Visual
1077 C++; to enable it, use the -fms-extensions command-line option. This is
1078 the default for Windows targets. Note that the support is incomplete;
1079 enabling Microsoft extensions will silently drop certain constructs
1080 (including ``__declspec`` and Microsoft-style asm statements).
1082 clang has a -fms-compatibility flag that makes clang accept enough
1083 invalid C++ to be able to parse most Microsoft headers. This flag is
1084 enabled by default for Windows targets.
1086 -fdelayed-template-parsing lets clang delay all template instantiation
1087 until the end of a translation unit. This flag is enabled by default for
1090 - clang allows setting ``_MSC_VER`` with ``-fmsc-version=``. It defaults to
1091 1300 which is the same as Visual C/C++ 2003. Any number is supported
1092 and can greatly affect what Windows SDK and c++stdlib headers clang
1093 can compile. This option will be removed when clang supports the full
1094 set of MS extensions required for these headers.
1095 - clang does not support the Microsoft extension where anonymous record
1096 members can be declared using user defined typedefs.
1097 - clang supports the Microsoft "#pragma pack" feature for controlling
1098 record layout. GCC also contains support for this feature, however
1099 where MSVC and GCC are incompatible clang follows the MSVC
1101 - clang defaults to C++11 for Windows targets.
1105 C++ Language Features
1106 =====================
1108 clang fully implements all of standard C++98 except for exported
1109 templates (which were removed in C++11), and `many C++11
1110 features <http://clang.llvm.org/cxx_status.html>`_ are also implemented.
1112 Controlling implementation limits
1113 ---------------------------------
1115 **-fconstexpr-depth=N**: Sets the limit for recursive constexpr function
1116 invocations to N. The default is 512.
1118 **-ftemplate-depth=N**: Sets the limit for recursively nested template
1119 instantiations to N. The default is 1024.
1123 Objective-C Language Features
1124 =============================
1128 Objective-C++ Language Features
1129 ===============================
1132 .. _target_features:
1134 Target-Specific Features and Limitations
1135 ========================================
1137 CPU Architectures Features and Limitations
1138 ------------------------------------------
1143 The support for X86 (both 32-bit and 64-bit) is considered stable on
1144 Darwin (Mac OS/X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
1145 to correctly compile many large C, C++, Objective-C, and Objective-C++
1148 On ``x86_64-mingw32``, passing i128(by value) is incompatible to Microsoft
1149 x64 calling conversion. You might need to tweak
1150 ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
1155 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
1156 on Darwin (iOS): it has been tested to correctly compile many large C,
1157 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
1158 limited number of ARM architectures. It does not yet fully support
1164 clang currently contains some support for PPC and Sparc; however,
1165 significant pieces of code generation are still missing, and they
1166 haven't undergone significant testing.
1168 clang contains limited support for the MSP430 embedded processor, but
1169 both the clang support and the LLVM backend support are highly
1172 Other platforms are completely unsupported at the moment. Adding the
1173 minimal support needed for parsing and semantic analysis on a new
1174 platform is quite easy; see lib/Basic/Targets.cpp in the clang source
1175 tree. This level of support is also sufficient for conversion to LLVM IR
1176 for simple programs. Proper support for conversion to LLVM IR requires
1177 adding code to lib/CodeGen/CGCall.cpp at the moment; this is likely to
1178 change soon, though. Generating assembly requires a suitable LLVM
1181 Operating System Features and Limitations
1182 -----------------------------------------
1192 Experimental supports are on Cygming.
1194 See also `Microsoft Extensions <c_ms>`.
1199 Clang works on Cygwin-1.7.
1204 Clang works on some mingw32 distributions. Clang assumes directories as
1207 - ``C:/mingw/include``
1209 - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
1211 On MSYS, a few tests might fail.
1216 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
1219 - ``GCC versions 4.5.0 to 4.5.3, 4.6.0 to 4.6.2, or 4.7.0 (for the C++ header search path)``
1220 - ``some_directory/bin/gcc.exe``
1221 - ``some_directory/bin/clang.exe``
1222 - ``some_directory/bin/clang++.exe``
1223 - ``some_directory/bin/../include/c++/GCC_version``
1224 - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
1225 - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
1226 - ``some_directory/bin/../include/c++/GCC_version/backward``
1227 - ``some_directory/bin/../x86_64-w64-mingw32/include``
1228 - ``some_directory/bin/../i686-w64-mingw32/include``
1229 - ``some_directory/bin/../include``
1231 This directory layout is standard for any toolchain you will find on the
1232 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
1234 Clang expects the GCC executable "gcc.exe" compiled for
1235 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
1237 `Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
1238 ``x86_64-w64-mingw32``.