blob: 6284255f87f66d39e3701388fa4622a947f307a2 [file] [log] [blame]
Sean Silva93ca0212012-12-13 01:10:46 +00001============================
2Clang Compiler User's Manual
3============================
4
5.. contents::
6 :local:
7
8Introduction
9============
10
11The Clang Compiler is an open-source compiler for the C family of
12programming languages, aiming to be the best in class implementation of
13these languages. Clang builds on the LLVM optimizer and code generator,
14allowing it to provide high-quality optimization and code generation
15support for many targets. For more general information, please see the
16`Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
17Site <http://llvm.org>`_.
18
19This document describes important notes about using Clang as a compiler
20for an end-user, documenting the supported features, command line
21options, etc. If you are interested in using Clang to build a tool that
22processes code, please see `the Clang Internals
23Manual <InternalsManual.html>`_. If you are interested in the `Clang
24Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
25page.
26
27Clang is designed to support the C family of programming languages,
28which 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
30language-specific information, please see the corresponding language
31specific section:
32
33- :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
34 C99 (+TC1, TC2, TC3).
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>`
39
40In addition to these base languages and their dialects, Clang supports a
41broad variety of language extensions, which are documented in the
42corresponding language section. These extensions are provided to be
43compatible with the GCC, Microsoft, and other popular compilers as well
44as to improve functionality through Clang-specific features. The Clang
45driver and language features are intentionally designed to be as
46compatible with the GNU GCC compiler as reasonably possible, easing
47migration from GCC to Clang. In most cases, code "just works".
48
49In addition to language specific features, Clang has a variety of
50features that depend on what CPU architecture or operating system is
51being compiled for. Please see the :ref:`Target-Specific Features and
52Limitations <target_features>` section for more details.
53
54The rest of the introduction introduces some basic :ref:`compiler
55terminology <terminology>` that is used throughout this manual and
56contains a basic :ref:`introduction to using Clang <basicusage>` as a
57command line compiler.
58
59.. _terminology:
60
61Terminology
62-----------
63
64Front end, parser, backend, preprocessor, undefined behavior,
65diagnostic, optimizer
66
67.. _basicusage:
68
69Basic Usage
70-----------
71
72Intro to how to use a C compiler for newbies.
73
74compile + link compile then link debug info enabling optimizations
75picking a language to use, defaults to C99 by default. Autosenses based
76on extension. using a makefile
77
78Command Line Options
79====================
80
81This section is generally an index into other sections. It does not go
82into depth on the ones that are covered by other sections. However, the
83first part introduces the language selection and other high level
84options like -c, -g, etc.
85
86Options to Control Error and Warning Messages
87---------------------------------------------
88
89**-Werror**: Turn warnings into errors.
90
91**-Werror=foo**: Turn warning "foo" into an error.
92
93**-Wno-error=foo**: Turn warning "foo" into an warning even if -Werror
94is specified.
95
96**-Wfoo**: Enable warning "foo".
97
98**-Wno-foo**: Disable warning "foo".
99
100**-w**: Disable all warnings.
101
102**-Weverything**: :ref:`Enable **all**
103warnings. <diagnostics_enable_everything>`
104
105**-pedantic**: Warn on language extensions.
106
107**-pedantic-errors**: Error on language extensions.
108
109**-Wsystem-headers**: Enable warnings from system headers.
110
111**-ferror-limit=123**: Stop emitting diagnostics after 123 errors have
112been produced. The default is 20, and the error limit can be disabled
113with -ferror-limit=0.
114
115**-ftemplate-backtrace-limit=123**: Only emit up to 123 template
116instantiation notes within the template instantiation backtrace for a
117single warning or error. The default is 10, and the limit can be
118disabled with -ftemplate-backtrace-limit=0.
119
120.. _cl_diag_formatting:
121
122Formatting of Diagnostics
123^^^^^^^^^^^^^^^^^^^^^^^^^
124
125Clang aims to produce beautiful diagnostics by default, particularly for
126new users that first come to Clang. However, different people have
127different preferences, and sometimes Clang is driven by another program
128that wants to parse simple and consistent output, not a person. For
129these cases, Clang provides a wide range of options to control the exact
130output format of the diagnostics that it generates.
131
132.. _opt_fshow-column:
133
134**-f[no-]show-column**
135 Print column number in diagnostic.
136
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:
140
141 ::
142
143 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
144 #endif bad
145 ^
146 //
147
148 When this is disabled, Clang will print "test.c:28: warning..." with
149 no column number.
150
151 The printed column numbers count bytes from the beginning of the
152 line; take care if your source contains multibyte characters.
153
154.. _opt_fshow-source-location:
155
156**-f[no-]show-source-location**
157 Print source file/line/column information in diagnostic.
158
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:
162
163 ::
164
165 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
166 #endif bad
167 ^
168 //
169
170 When this is disabled, Clang will not print the "test.c:28:8: "
171 part.
172
173.. _opt_fcaret-diagnostics:
174
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
180 something like:
181
182 ::
183
184 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
185 #endif bad
186 ^
187 //
188
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.
192
193 When this option is enabled, Clang will use colors to highlight
194 specific parts of the diagnostic, e.g.,
195
196 .. nasty hack to not lose our dignity
197
198 .. raw:: html
199
200 <pre>
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>
202 #endif bad
203 <span style="color:green">^</span>
204 <span style="color:green">//</span>
205 </pre>
206
207 When this is disabled, Clang will just print:
208
209 ::
210
211 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
212 #endif bad
213 ^
214 //
215
216**-fdiagnostics-format=clang/msvc/vi**
217 Changes diagnostic output format to better match IDEs and command line tools.
218
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:
222
223 **clang** (default)
224 ::
225
226 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
227
228 **msvc**
229 ::
230
231 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
232
233 **vi**
234 ::
235
236 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
237
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.
242
243.. _opt_fdiagnostics-show-option:
244
245**-f[no-]diagnostics-show-option**
246 Enable ``[-Woption]`` information in diagnostic line.
247
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
251 this output:
252
253 ::
254
255 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
256 #endif bad
257 ^
258 //
259
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>`.
265
266.. _opt_fdiagnostics-show-category:
267
268**-fdiagnostics-show-category=none/id/name**
269 Enable printing category information in diagnostic line.
270
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).
276
277 For example, a format string warning will produce these three
278 renditions based on the setting of this option:
279
280 ::
281
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]
285
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.
289
290.. _opt_fdiagnostics-fixit-info:
291
292**-f[no-]diagnostics-fixit-info**
293 Enable "FixIt" information in the diagnostics output.
294
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:
298
299 ::
300
301 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
302 #endif bad
303 ^
304 //
305
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.
310
311.. _opt_fdiagnostics-print-source-range-info:
312
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:
320
321 ::
322
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;
325 ~~~~~~ ^ ~~~~~~~
326
327 The {}'s are generated by -fdiagnostics-print-source-range-info.
328
329 The printed column numbers count bytes from the beginning of the
330 line; take care if your source contains multibyte characters.
331
332**-fdiagnostics-parseable-fixits**
333 Print Fix-Its in a machine parseable form.
334
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:
338
339 ::
340
341 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
342
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").
351
352 The printed column numbers count bytes from the beginning of the
353 line; take care if your source contains multibyte characters.
354
355**-fno-elide-type**
356 Turns off elision in template type printing.
357
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.
363
364 Default:
365
366 ::
367
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;
369
370 -fno-elide-type:
371
372 ::
373
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;
375
376**-fdiagnostics-show-template-tree**
377 Template type diffing prints a text tree.
378
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
382 -fno-elide-type.
383
384 Default:
385
386 ::
387
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;
389
390 -fdiagnostics-show-template-tree
391
392 ::
393
394 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
395 vector<
396 map<
397 [...],
398 map<
399 [float != float],
400 [...]>>>
401
402.. _cl_diag_warning_groups:
403
404Individual Warning Groups
405^^^^^^^^^^^^^^^^^^^^^^^^^
406
407TODO: Generate this from tblgen. Define one anchor per warning group.
408
409.. _opt_wextra-tokens:
410
411**-Wextra-tokens**
412 Warn about excess tokens at the end of a preprocessor directive.
413
414 This option, which defaults to on, enables warnings about extra
415 tokens at the end of preprocessor directives. For example:
416
417 ::
418
419 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
420 #endif bad
421 ^
422
423 These extra tokens are not strictly conforming, and are usually best
424 handled by commenting them out.
425
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.
429
430 This option, which defaults to on, enables a warning in the
431 following code:
432
433 ::
434
435 template<typename T> struct set{};
436 template<typename T> struct trait { typedef const T& type; };
437 struct Value {
438 template<typename T> void set(typename trait<T>::type value) {}
439 };
440 void foo() {
441 Value v;
442 v.set<double>(3.2);
443 }
444
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
447 as an extension.
448
449**-Wbind-to-temporary-copy**
450 Warn about an unusable copy constructor when binding a reference to a
451 temporary.
452
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:
456
457 ::
458
459 struct NonCopyable {
460 NonCopyable();
461 private:
462 NonCopyable(const NonCopyable&);
463 };
464 void foo(const NonCopyable&);
465 void bar() {
466 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
467 }
468
469 ::
470
471 struct NonCopyable2 {
472 NonCopyable2();
473 NonCopyable2(NonCopyable2&);
474 };
475 void foo(const NonCopyable2&);
476 void bar() {
477 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
478 }
479
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.
483
484Options to Control Clang Crash Diagnostics
485------------------------------------------
486
487As unbelievable as it may sound, Clang does crash from time to time.
488Generally, this only occurs to those living on the `bleeding
489edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
490lengths to assist you in filing a bug report. Specifically, Clang
491generates preprocessed source file(s) and associated run script(s) upon
492a crash. These files should be attached to a bug report to ease
493reproducibility of the failure. Below are the command line options to
494control the crash diagnostics.
495
496**-fno-crash-diagnostics**: Disable auto-generation of preprocessed
497source files during a clang crash.
498
499The -fno-crash-diagnostics flag can be helpful for speeding the process
500of generating a delta reduced test case.
501
502Language and Target-Independent Features
503========================================
504
505Controlling Errors and Warnings
506-------------------------------
507
508Clang provides a number of ways to control which code constructs cause
509it to emit errors and warning messages, and how they are displayed to
510the console.
511
512Controlling How Clang Displays Diagnostics
513^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
514
515When Clang emits a diagnostic, it includes rich information in the
516output, and gives you fine-grain control over which information is
517printed. Clang has the ability to print this information, and these are
518the options that control it:
519
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
524 fatal error.
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
531 that support it)
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
540 default)
541 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
542
543For more information please see :ref:`Formatting of
544Diagnostics <cl_diag_formatting>`.
545
546Diagnostic Mappings
547^^^^^^^^^^^^^^^^^^^
548
549All diagnostics are mapped into one of these 5 classes:
550
551- Ignored
552- Note
553- Warning
554- Error
555- Fatal
556
557.. _diagnostics_categories:
558
559Diagnostic Categories
560^^^^^^^^^^^^^^^^^^^^^
561
562Though not shown by default, diagnostics may each be associated with a
563high-level category. This category is intended to make it possible to
564triage builds that produce a large number of errors or warnings in a
565grouped way.
566
567Categories are not shown by default, but they can be turned on with the
568:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
569When set to "``name``", the category is printed textually in the
570diagnostic output. When it is set to "``id``", a category number is
571printed. The mapping of category names to category id's can be obtained
572by running '``clang --print-diagnostic-categories``'.
573
574Controlling Diagnostics via Command Line Flags
575^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
576
577TODO: -W flags, -pedantic, etc
578
579.. _pragma_gcc_diagnostic:
580
581Controlling Diagnostics via Pragmas
582^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
583
584Clang can also control what diagnostics are enabled through the use of
585pragmas in the source code. This is useful for turning off specific
586warnings in a section of source code. Clang supports GCC's pragma for
587compatibility with existing source code, as well as several extensions.
588
589The pragma may control any warning that can be used from the command
590line. Warnings may be set to ignored, warning, error, or fatal. The
591following example code will tell Clang or GCC to ignore the -Wall
592warnings:
593
594::
595
596 #pragma GCC diagnostic ignored "-Wall"
597
598In addition to all of the functionality provided by GCC's pragma, Clang
599also allows you to push and pop the current warning state. This is
600particularly useful when writing a header file that will be compiled by
601other people, because you don't know what warning flags they build with.
602
603In the below example -Wmultichar is ignored for only a single line of
604code, after which the diagnostics return to whatever state had
605previously existed.
606
607::
608
609 #pragma clang diagnostic push
610 #pragma clang diagnostic ignored "-Wmultichar"
611
612 char b = 'df'; // no warning.
613
614 #pragma clang diagnostic pop
615
616The push and pop pragmas will save and restore the full diagnostic state
617of the compiler, regardless of how it was set. That means that it is
618possible to use push and pop around GCC compatible diagnostics and Clang
619will push and pop them appropriately, while GCC will ignore the pushes
620and pops as unknown pragmas. It should be noted that while Clang
621supports the GCC pragma, Clang and GCC do not support the exact same set
622of warnings, so even when using GCC compatible #pragmas there is no
623guarantee that they will have identical behaviour on both compilers.
624
625Controlling Diagnostics in System Headers
626^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
627
628Warnings are suppressed when they occur in system headers. By default,
629an included file is treated as a system header if it is found in an
630include path specified by ``-isystem``, but this can be overridden in
631several ways.
632
633The ``system_header`` pragma can be used to mark the current file as
634being a system header. No warnings will be produced from the location of
635the pragma onwards within the same file.
636
637::
638
639 char a = 'xy'; // warning
640
641 #pragma clang system_header
642
643 char b = 'ab'; // no warning
644
645The ``-isystem-prefix`` and ``-ino-system-prefix`` command-line
646arguments can be used to override whether subsets of an include path are
647treated as system headers. When the name in a ``#include`` directive is
648found within a header search path and starts with a system prefix, the
649header is treated as a system header. The last prefix on the
650command-line which matches the specified header name takes precedence.
651For instance:
652
653::
654
655 clang -Ifoo -isystem bar -isystem-prefix x/ -ino-system-prefix x/y/
656
657Here, ``#include "x/a.h"`` is treated as including a system header, even
658if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
659as not including a system header, even if the header is found in
660``bar``.
661
662A ``#include`` directive which finds a file relative to the current
663directory is treated as including a system header if the including file
664is treated as a system header.
665
666.. _diagnostics_enable_everything:
667
668Enabling All Warnings
669^^^^^^^^^^^^^^^^^^^^^
670
671In addition to the traditional ``-W`` flags, one can enable **all**
672warnings by passing ``-Weverything``. This works as expected with
673``-Werror``, and also includes the warnings from ``-pedantic``.
674
675Note that when combined with ``-w`` (which disables all warnings), that
676flag wins.
677
678Controlling Static Analyzer Diagnostics
679^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
680
681While not strictly part of the compiler, the diagnostics from Clang's
682`static analyzer <http://clang-analyzer.llvm.org>`_ can also be
683influenced by the user via changes to the source code. See the available
684`annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
685analyzer's `FAQ
686page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
687information.
688
689Precompiled Headers
690-------------------
691
692`Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
693are a general approach employed by many compilers to reduce compilation
694time. The underlying motivation of the approach is that it is common for
695the same (and often large) header files to be included by multiple
696source files. Consequently, compile times can often be greatly improved
697by caching some of the (redundant) work done by a compiler to process
698headers. Precompiled header files, which represent one of many ways to
699implement this optimization, are literally files that represent an
700on-disk cache that contains the vital information necessary to reduce
701some of the work needed to process a corresponding header file. While
702details of precompiled headers vary between compilers, precompiled
703headers have been shown to be highly effective at speeding up program
704compilation on systems with very large system headers (e.g., Mac OS/X).
705
706Generating a PCH File
707^^^^^^^^^^^^^^^^^^^^^
708
709To generate a PCH file using Clang, one invokes Clang with the
710**``-x <language>-header``** option. This mirrors the interface in GCC
711for generating PCH files:
712
713::
714
715 $ gcc -x c-header test.h -o test.h.gch
716 $ clang -x c-header test.h -o test.h.pch
717
718Using a PCH File
719^^^^^^^^^^^^^^^^
720
721A PCH file can then be used as a prefix header when a **``-include``**
722option is passed to ``clang``:
723
724::
725
726 $ clang -include test.h test.c -o test
727
728The ``clang`` driver will first check if a PCH file for ``test.h`` is
729available; if so, the contents of ``test.h`` (and the files it includes)
730will be processed from the PCH file. Otherwise, Clang falls back to
731directly processing the content of ``test.h``. This mirrors the behavior
732of GCC.
733
734.. note::
735 Clang does *not* automatically use PCH files for headers that are
736 directly included within a source file. For example:
737
738::
739
740 $ clang -x c-header test.h -o test.h.pch
741 $ cat test.c
742 #include "test.h"
743 $ clang test.c -o test
744
745In 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
747not specified on the command line using ``-include``.
748
749Relocatable PCH Files
750^^^^^^^^^^^^^^^^^^^^^
751
752It is sometimes necessary to build a precompiled header from headers
753that are not yet in their final, installed locations. For example, one
754might build a precompiled header within the build tree that is then
755meant to be installed alongside the headers. Clang permits the creation
756of "relocatable" precompiled headers, which are built with a given path
757(into the build directory) and can later be used from an installed
758location.
759
760To build a relocatable precompiled header, place your headers into a
761subdirectory whose structure mimics the installed location. For example,
762if you want to build a precompiled header for the header ``mylib.h``
763that will be installed into ``/usr/include``, create a subdirectory
764``build/usr/include`` and place the header ``mylib.h`` into that
765subdirectory. If ``mylib.h`` depends on other headers, then they can be
766stored within ``build/usr/include`` in a way that mimics the installed
767location.
768
769Building a relocatable precompiled header requires two additional
770arguments. First, pass the ``--relocatable-pch`` flag to indicate that
771the resulting PCH file should be relocatable. Second, pass
772``-isysroot /path/to/build``, which makes all includes for your library
773relative to the build directory. For example:
774
775::
776
777 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
778
779When loading the relocatable PCH file, the various headers used in the
780PCH file are found from the system header root. For example, ``mylib.h``
781can be found in ``/usr/include/mylib.h``. If the headers are installed
782in some other system root, the ``-isysroot`` option can be used provide
783a different system root from which the headers will be based. For
784example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
785``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
786
787Relocatable precompiled headers are intended to be used in a limited
788number of cases where the compilation environment is tightly controlled
789and the precompiled header cannot be generated after headers have been
790installed. Relocatable precompiled headers also have some performance
791impact, because the difference in location between the header locations
792at PCH build time vs. at the time of PCH use requires one of the PCH
793optimizations, ``stat()`` caching, to be disabled. However, this change
794is only likely to affect PCH files that reference a large number of
795headers.
796
797Controlling Code Generation
798---------------------------
799
800Clang provides a number of ways to control code generation. The options
801are listed below.
802
803**-fsanitize=check1,check2**
804 Turn on runtime checks for various forms of undefined or suspicious
805 behavior.
806
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:
811
812 .. _opt_fsanitize_address:
813
814 - ``-fsanitize=address``:
815 :doc:`AddressSanitizer`, a memory error
816 detector.
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
823 use.
824
825 .. _opt_fsanitize_undefined:
826
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``.
832
833 The following more fine-grained checks are also available:
834
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
841 destination.
842 - ``-fsanitize=float-divide-by-zero``: Floating point division by
843 zero.
844 - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
845 - ``-fsanitize=null``: Use of a null pointer or creation of a null
846 reference.
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
865 overflows.
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``.
871
872 Experimental features of AddressSanitizer (not ready for widespread
873 use, require explicit ``-fsanitize=address``):
874
875 - ``-fsanitize=init-order``: Check for dynamic initialization order
876 problems.
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).
881
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.
897
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.
901
902**-ftrap-function=[name]**
903 Instruct code generator to emit a function call to the specified
904 function name for ``__builtin_trap()``.
905
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.
914
915**-ftls-model=[model]**
916 Select which TLS model to use.
917
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.
924
925Controlling Size of Debug Information
926-------------------------------------
927
928Debug info kind generated by Clang can be set by one of the flags listed
929below. If multiple flags are present, the last one is used.
930
931**-g0**: Don't generate any debug info (default).
932
933**-gline-tables-only**: Generate line number tables only.
934
935This kind of debug info allows to obtain stack traces with function
936names, file names and line numbers (by such tools as gdb or addr2line).
937It doesn't contain any other data (e.g. description of local variables
938or function parameters).
939
940**-g**: Generate complete debug info.
941
942.. _c:
943
944C Language Features
945===================
946
947The support for standard C in clang is feature-complete except for the
948C99 floating-point pragmas.
949
950Extensions supported by clang
951-----------------------------
952
953See `clang language extensions <LanguageExtensions.html>`_.
954
955Differences between various standard modes
956------------------------------------------
957
958clang supports the -std option, which changes what language mode clang
959uses. The supported modes for C are c89, gnu89, c94, c99, gnu99 and
960various aliases for those modes. If no -std option is specified, clang
961defaults to gnu99 mode.
962
963Differences between all ``c*`` and ``gnu*`` modes:
964
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
972 modes.
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"
975 option.
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.
980
981Differences between ``*89`` and ``*99`` modes:
982
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__``
986 attribute.
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
990 x;}*)0) {}``".)
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
996 in ``*89`` modes.
997- Some warnings are different.
998
999c94 mode is identical to c89 mode except that digraphs are enabled in
1000c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1001
1002GCC extensions not implemented yet
1003----------------------------------
1004
1005clang tries to be compatible with gcc as much as possible, but some gcc
1006extensions are not implemented yet:
1007
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,
1011 at least partially.
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:
1020
1021 ::
1022
1023 auto const local_function = [&](int parameter) {
1024 // Do something
1025 };
1026 ...
1027 local_function(1);
1028
1029- clang does not support global register variables; this is unlikely to
1030 be implemented soon because it requires additional LLVM backend
1031 support.
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.
1045
1046This is not a complete list; if you find an unsupported extension
1047missing from this list, please send an e-mail to cfe-dev. This list
1048currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1049list does not include bugs in mostly-implemented features; please see
1050the `bug
1051tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
1052for known existing bugs (FIXME: Is there a section for bug-reporting
1053guidelines somewhere?).
1054
1055Intentionally unsupported GCC extensions
1056----------------------------------------
1057
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
1067 variable.
1068- clang does not support ``__builtin_apply`` and friends; this extension
1069 is extremely obscure and difficult to implement reliably.
1070
1071.. _c_ms:
1072
1073Microsoft extensions
1074--------------------
1075
1076clang has some experimental support for extensions from Microsoft Visual
1077C++; to enable it, use the -fms-extensions command-line option. This is
1078the default for Windows targets. Note that the support is incomplete;
1079enabling Microsoft extensions will silently drop certain constructs
1080(including ``__declspec`` and Microsoft-style asm statements).
1081
1082clang has a -fms-compatibility flag that makes clang accept enough
1083invalid C++ to be able to parse most Microsoft headers. This flag is
1084enabled by default for Windows targets.
1085
1086-fdelayed-template-parsing lets clang delay all template instantiation
1087until the end of a translation unit. This flag is enabled by default for
1088Windows targets.
1089
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
1100 definition.
1101- clang defaults to C++11 for Windows targets.
1102
1103.. _cxx:
1104
1105C++ Language Features
1106=====================
1107
1108clang fully implements all of standard C++98 except for exported
1109templates (which were removed in C++11), and `many C++11
1110features <http://clang.llvm.org/cxx_status.html>`_ are also implemented.
1111
1112Controlling implementation limits
1113---------------------------------
1114
1115**-fconstexpr-depth=N**: Sets the limit for recursive constexpr function
1116invocations to N. The default is 512.
1117
1118**-ftemplate-depth=N**: Sets the limit for recursively nested template
1119instantiations to N. The default is 1024.
1120
1121.. _objc:
1122
1123Objective-C Language Features
1124=============================
1125
1126.. _objcxx:
1127
1128Objective-C++ Language Features
1129===============================
1130
1131
1132.. _target_features:
1133
1134Target-Specific Features and Limitations
1135========================================
1136
1137CPU Architectures Features and Limitations
1138------------------------------------------
1139
1140X86
1141^^^
1142
1143The support for X86 (both 32-bit and 64-bit) is considered stable on
1144Darwin (Mac OS/X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
1145to correctly compile many large C, C++, Objective-C, and Objective-C++
1146codebases.
1147
1148On ``x86_64-mingw32``, passing i128(by value) is incompatible to Microsoft
1149x64 calling conversion. You might need to tweak
1150``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
1151
1152ARM
1153^^^
1154
1155The support for ARM (specifically ARMv6 and ARMv7) is considered stable
1156on Darwin (iOS): it has been tested to correctly compile many large C,
1157C++, Objective-C, and Objective-C++ codebases. Clang only supports a
1158limited number of ARM architectures. It does not yet fully support
1159ARMv5, for example.
1160
1161Other platforms
1162^^^^^^^^^^^^^^^
1163
1164clang currently contains some support for PPC and Sparc; however,
1165significant pieces of code generation are still missing, and they
1166haven't undergone significant testing.
1167
1168clang contains limited support for the MSP430 embedded processor, but
1169both the clang support and the LLVM backend support are highly
1170experimental.
1171
1172Other platforms are completely unsupported at the moment. Adding the
1173minimal support needed for parsing and semantic analysis on a new
1174platform is quite easy; see lib/Basic/Targets.cpp in the clang source
1175tree. This level of support is also sufficient for conversion to LLVM IR
1176for simple programs. Proper support for conversion to LLVM IR requires
1177adding code to lib/CodeGen/CGCall.cpp at the moment; this is likely to
1178change soon, though. Generating assembly requires a suitable LLVM
1179backend.
1180
1181Operating System Features and Limitations
1182-----------------------------------------
1183
1184Darwin (Mac OS/X)
1185^^^^^^^^^^^^^^^^^
1186
1187None
1188
1189Windows
1190^^^^^^^
1191
1192Experimental supports are on Cygming.
1193
1194See also `Microsoft Extensions <c_ms>`.
1195
1196Cygwin
1197""""""
1198
1199Clang works on Cygwin-1.7.
1200
1201MinGW32
1202"""""""
1203
1204Clang works on some mingw32 distributions. Clang assumes directories as
1205below;
1206
1207- ``C:/mingw/include``
1208- ``C:/mingw/lib``
1209- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
1210
1211On MSYS, a few tests might fail.
1212
1213MinGW-w64
1214"""""""""
1215
1216For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
1217assumes as below;
1218
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``
1230
1231This directory layout is standard for any toolchain you will find on the
1232official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
1233
1234Clang expects the GCC executable "gcc.exe" compiled for
1235``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
1236
1237`Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
1238``x86_64-w64-mingw32``.