blob: b2734874520aae909add5e31213b11765c68ed6e [file] [log] [blame]
Douglas Gregorc41b6ff2010-06-30 22:01:08 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3<html>
4<head>
5 <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
6 <title>Language Compatibility</title>
7 <link type="text/css" rel="stylesheet" href="menu.css" />
8 <link type="text/css" rel="stylesheet" href="content.css" />
9 <style type="text/css">
10</style>
11</head>
12<body>
13
14<!--#include virtual="menu.html.incl"-->
15
16<div id="content">
17
18<!-- ======================================================================= -->
19<h1>Language Compatibility</h1>
20<!-- ======================================================================= -->
21
22<p>Clang strives to both conform to current language standards (C99,
23 C++98) and also to implement many widely-used extensions available
24 in other compilers, so that most correct code will "just work" when
25 compiler with Clang. However, Clang is more strict than other
26 popular compilers, and may reject incorrect code that other
27 compilers allow. This page documents common compatibility and
28 portability issues with Clang to help you understand and fix the
29 problem in your code when Clang emits an error message.</p>
30
31<ul>
32 <li><a href="#c">C compatibility</a>
33 <ul>
34 <li><a href="#inline">C99 inline functions</a></li>
Chris Lattnera02d1832010-09-16 18:17:55 +000035 <li><a href="#vector_builtins">"missing" vector __builtin functions</a></li>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +000036 <li><a href="#lvalue-cast">Lvalue casts</a></li>
Daniel Dunbar5a410212010-09-02 21:35:16 +000037 <li><a href="#blocks-in-protected-scope">Jumps to within <tt>__block</tt> variable scope</a></li>
Daniel Dunbar15952c92010-11-09 22:45:16 +000038 <li><a href="#block-variable-initialization">Non-initialization of <tt>__block</tt> variables</a></li>
Chris Lattner9b743f42010-11-10 23:51:50 +000039 <li><a href="#inline-asm">Inline assembly</a></li>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +000040 </ul>
41 </li>
42 <li><a href="#objective-c">Objective-C compatibility</a>
43 <ul>
44 <li><a href="#super-cast">Cast of super</a></li>
45 <li><a href="#sizeof-interface">Size of interfaces</a></li>
Argyrios Kyrtzidis3b5b92a2010-09-13 17:48:07 +000046 <li><a href="#objc_objs-cast">Internal Objective-C types</a></li>
Fariborz Jahanianddfa6c32010-10-22 22:35:51 +000047 <li><a href="#c_variables-class">C variables in @class or @protocol</a></li>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +000048 </ul>
49 </li>
50 <li><a href="#c++">C++ compatibility</a>
51 <ul>
52 <li><a href="#vla">Variable-length arrays</a></li>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +000053 <li><a href="#dep_lookup">Unqualified lookup in templates</a></li>
54 <li><a href="#dep_lookup_bases">Unqualified lookup into dependent bases of class templates</a></li>
55 <li><a href="#undep_incomplete">Incomplete types in templates</a></li>
56 <li><a href="#bad_templates">Templates with no valid instantiations</a></li>
57 <li><a href="#default_init_const">Default initialization of const
58 variable of a class type requires user-defined default
59 constructor</a></li>
Douglas Gregora66d3bb2010-11-10 20:24:21 +000060 <li><a href="#param_name_lookup">Parameter name lookup</a></li>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +000061 </ul>
62 </li>
63 <li><a href="#objective-c++">Objective-C++ compatibility</a>
64 <ul>
65 <li><a href="#implicit-downcasts">Implicit downcasts</a></li>
66 </ul>
Fariborz Jahanian36e738a2010-08-11 18:57:26 +000067 <ul>
68 <li><a href="#Use of class as method name">Use of class as method name</a></li>
69 </ul>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +000070 </li>
71</ul>
72
73<!-- ======================================================================= -->
74<h2 id="c">C compatibility</h3>
75<!-- ======================================================================= -->
76
77<!-- ======================================================================= -->
78<h3 id="inline">C99 inline functions</h3>
79<!-- ======================================================================= -->
80<p>By default, Clang builds C code according to the C99 standard,
John McCall5ae84f22011-02-03 10:16:40 +000081which provides different semantics for the <code>inline</code> keyword
82than GCC's default behavior. For example, consider the following
83code:</p>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +000084<pre>
85inline int add(int i, int j) { return i + j; }
86
87int main() {
88 int i = add(4, 5);
89 return i;
90}
91</pre>
92
John McCall5ae84f22011-02-03 10:16:40 +000093<p>In C99, <code>inline</code> means that a function's definition is
94provided only for inlining, and that there is another definition
95(without <code>inline</code>) somewhere else in the program. That
96means that this program is incomplete, because if <code>add</code>
97isn't inlined (for example, when compiling without optimization), then
98<code>main</code> will have an unresolved reference to that other
99definition. Therefore we'll get a (correct) link-time error like this:</p>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000100
101<pre>
102Undefined symbols:
103 "_add", referenced from:
104 _main in cc-y1jXIr.o
105</pre>
106
John McCall5ae84f22011-02-03 10:16:40 +0000107<p>By contrast, GCC's default behavior follows the GNU89 dialect,
108which is the C89 standard plus a lot of extensions. C89 doesn't have
109an <code>inline</code> keyword, but GCC recognizes it as an extension
110and just treats it as a hint to the optimizer.</p>
111
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000112<p>There are several ways to fix this problem:</p>
113
114<ul>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000115 <li>Change <code>add</code> to a <code>static inline</code>
John McCall5ae84f22011-02-03 10:16:40 +0000116 function. This is usually the right solution if only one
117 translation unit needs to use the function. <code>static
118 inline</code> functions are always resolved within the translation
119 unit, so you won't have to add a non-<code>inline</code> definition
120 of the function elsewhere in your program.</li>
121
122 <li>Remove the <code>inline</code> keyword from this definition of
123 <code>add</code>. The <code>inline</code> keyword is not required
124 for a function to be inlined, nor does it guarantee that it will be.
125 Some compilers ignore it completely. Clang treats it as a mild
126 suggestion from the programmer.</li>
127
128 <li>Provide an external (non-<code>inline</code>) definition
129 of <code>add</code> somewhere else in your program. The two
130 definitions must be equivalent!</li>
131
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000132 <li>Compile with the GNU89 dialect by adding
133 <code>-std=gnu89</code> to the set of Clang options. This option is
134 only recommended if the program source cannot be changed or if the
135 program also relies on additional C89-specific behavior that cannot
136 be changed.</li>
137</ul>
138
John McCall5ae84f22011-02-03 10:16:40 +0000139<p>All of this only applies to C code; the meaning of <code>inline</code>
140in C++ is very different from its meaning in either GNU89 or C99.</p>
Chris Lattnera02d1832010-09-16 18:17:55 +0000141
142<!-- ======================================================================= -->
143<h3 id="vector_builtins">"missing" vector __builtin functions</h3>
144<!-- ======================================================================= -->
145
146<p>The Intel and AMD manuals document a number "<tt>&lt;*mmintrin.h&gt;</tt>"
147header files, which define a standardized API for accessing vector operations
148on X86 CPUs. These functions have names like <tt>_mm_xor_ps</tt> and
149<tt>_mm256_addsub_pd</tt>. Compilers have leeway to implement these functions
150however they want. Since Clang supports an excellent set of <a
151href="../docs/LanguageExtensions.html#vectors">native vector operations</a>,
152the Clang headers implement these interfaces in terms of the native vector
153operations.
154</p>
155
156<p>In contrast, GCC implements these functions mostly as a 1-to-1 mapping to
157builtin function calls, like <tt>__builtin_ia32_paddw128</tt>. These builtin
158functions are an internal implementation detail of GCC, and are not portable to
159the Intel compiler, the Microsoft compiler, or Clang. If you get build errors
160mentioning these, the fix is simple: switch to the *mmintrin.h functions.</p>
161
162<p>The same issue occurs for NEON and Altivec for the ARM and PowerPC
163architectures respectively. For these, make sure to use the &lt;arm_neon.h&gt;
164and &lt;altivec.h&gt; headers.</p>
165
Eric Christophera473c952010-10-25 21:17:59 +0000166<p>For x86 architectures this <a href="builtins.py">script</a> should help with
167the manual migration process. It will rewrite your source files in place to
168use the APIs instead of builtin function calls. Just call it like this:</p>
169
170<pre>
171 builtins.py *.c *.h
172</pre>
173
174<p>and it will rewrite all of the .c and .h files in the current directory to
175use the API calls instead of calls like <tt>__builtin_ia32_paddw128</tt>.</p>
Chris Lattnera02d1832010-09-16 18:17:55 +0000176
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000177<!-- ======================================================================= -->
178<h3 id="lvalue-cast">Lvalue casts</h3>
179<!-- ======================================================================= -->
180
Douglas Gregor6f1adba2010-06-30 22:38:37 +0000181<p>Old versions of GCC permit casting the left-hand side of an assignment to a
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000182different type. Clang produces an error on similar code, e.g.,</p>
183
184<pre>
185lvalue.c:2:3: error: assignment to cast is illegal, lvalue casts are not
186 supported
187 (int*)addr = val;
188 ^~~~~~~~~~ ~
189</pre>
190
191<p>To fix this problem, move the cast to the right-hand side. In this
192example, one could use:</p>
193
194<pre>
195 addr = (float *)val;
196</pre>
197
198<!-- ======================================================================= -->
Daniel Dunbar5a410212010-09-02 21:35:16 +0000199<h3 id="blocks-in-protected-scope">Jumps to within <tt>__block</tt> variable scope</h3>
200<!-- ======================================================================= -->
201
202<p>Clang disallows jumps into the scope of a <tt>__block</tt> variable, similar
203to the manner in which both GCC and Clang disallow jumps into the scope of
204variables which have user defined constructors (in C++).</p>
205
206<p>Variables marked with <tt>__block</tt> require special runtime initialization
207before they can be used. A jump into the scope of a <tt>__block</tt> variable
208would bypass this initialization and therefore the variable cannot safely be
209used.</p>
210
211<p>For example, consider the following code fragment:</p>
212
213<pre>
214int f0(int c) {
215 if (c)
216 goto error;
217
218 __block int x;
219 x = 1;
220 return x;
221
222 error:
223 x = 0;
224 return x;
225}
226</pre>
227
228<p>GCC accepts this code, but it will crash at runtime along the error path,
229because the runtime setup for the storage backing the <tt>x</tt> variable will
230not have been initialized. Clang rejects this code with a hard error:</p>
231
232<pre>
233t.c:3:5: error: goto into protected scope
234 goto error;
235 ^
236t.c:5:15: note: jump bypasses setup of __block variable
237 __block int x;
238 ^
239</pre>
240
241<p>Some instances of this construct may be safe if the variable is never used
242after the jump target, however the protected scope checker does not check the
Daniel Dunbar55f1da82010-09-03 00:41:43 +0000243uses of the variable, only the scopes in which it is visible. You should rewrite
Daniel Dunbar5a410212010-09-02 21:35:16 +0000244your code to put the <tt>__block</tt> variables in a scope which is only visible
245where they are used.</p>
246
247<!-- ======================================================================= -->
Daniel Dunbar15952c92010-11-09 22:45:16 +0000248<h3 id="block-variable-initialization">Non-initialization of <tt>__block</tt>
249variables</h3>
250<!-- ======================================================================= -->
251
252<p>In the following example code, the <tt>x</tt> variable is used before it is
253defined:</p>
254<pre>
255int f0() {
256 __block int x;
257 return ^(){ return x; }();
258}
259</pre>
260
261<p>By an accident of implementation, GCC and llvm-gcc unintentionally always
262zero initialized <tt>__block</tt> variables. However, any program which depends
263on this behavior is relying on unspecified compiler behavior. Programs must
264explicitly initialize all local block variables before they are used, as with
265other local variables.</p>
266
267<p>Clang does not zero initialize local block variables, and programs which rely
268on such behavior will most likely break when built with Clang.</p>
269
Chris Lattner9b743f42010-11-10 23:51:50 +0000270
271<!-- ======================================================================= -->
272<h3 id="inline-asm">Inline assembly</h3>
273<!-- ======================================================================= -->
274
275<p>In general, Clang is highly compatible with the GCC inline assembly
276extensions, allowing the same set of constraints, modifiers and operands as GCC
277inline assembly.</p>
278
279<p>On targets that use the integrated assembler (such as most X86 targets),
280inline assembly is run through the integrated assembler instead of your system
281assembler (which is most commonly "gas", the GNU assembler). The LLVM
282integrated assembler is extremely compatible with GAS, but there are a couple of
283minor places where it is more picky, particularly due to outright GAS bugs.</p>
284
285<p>One specific example is that the assembler rejects ambiguous X86 instructions
286that don't have suffixes. For example:</p>
287
288<pre>
289 asm("add %al, (%rax)");
290 asm("addw $4, (%rax)");
291 asm("add $4, (%rax)");
292</pre>
293
294<p>Both clang and GAS accept the first instruction: because the first
295instruction uses the 8-bit <tt>%al</tt> register as an operand, it is clear that
296it is an 8-bit add. The second instruction is accepted by both because the "w"
297suffix indicates that it is a 16-bit add. The last instruction is accepted by
298GAS even though there is nothing that specifies the size of the instruction (and
299the assembler randomly picks a 32-bit add). Because it is ambiguous, Clang
300rejects the instruction with this error message:
301</p>
302
303<pre>
304&lt;inline asm&gt;:3:1: error: ambiguous instructions require an explicit suffix (could be 'addb', 'addw', 'addl', or 'addq')
305add $4, (%rax)
306^
3071 error generated.
308</pre>
309
310<p>To fix this compatibility issue, add an explicit suffix to the instruction:
311this makes your code more clear and is compatible with both GCC and Clang.</p>
312
Daniel Dunbar15952c92010-11-09 22:45:16 +0000313<!-- ======================================================================= -->
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000314<h2 id="objective-c">Objective-C compatibility</h3>
315<!-- ======================================================================= -->
316
317<!-- ======================================================================= -->
318<h3 id="super-cast">Cast of super</h3>
319<!-- ======================================================================= -->
320
321<p>GCC treats the <code>super</code> identifier as an expression that
322can, among other things, be cast to a different type. Clang treats
323<code>super</code> as a context-sensitive keyword, and will reject a
324type-cast of <code>super</code>:</p>
325
326<pre>
327super.m:11:12: error: cannot cast 'super' (it isn't an expression)
328 [(Super*)super add:4];
329 ~~~~~~~~^
330</pre>
331
332<p>To fix this problem, remove the type cast, e.g.</p>
333<pre>
334 [super add:4];
335</pre>
336
337<!-- ======================================================================= -->
338<h3 id="sizeof-interface">Size of interfaces</h3>
339<!-- ======================================================================= -->
340
341<p>When using the "non-fragile" Objective-C ABI in use, the size of an
342Objective-C class may change over time as instance variables are added
343(or removed). For this reason, Clang rejects the application of the
344<code>sizeof</code> operator to an Objective-C class when using this
345ABI:</p>
346
347<pre>
348sizeof.m:4:14: error: invalid application of 'sizeof' to interface 'NSArray' in
349 non-fragile ABI
350 int size = sizeof(NSArray);
351 ^ ~~~~~~~~~
352</pre>
353
354<p>Code that relies on the size of an Objective-C class is likely to
355be broken anyway, since that size is not actually constant. To address
356this problem, use the Objective-C runtime API function
Benjamin Kramere6617502010-06-30 22:29:56 +0000357<code>class_getInstanceSize()</code>:</p>
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000358
359<pre>
360 class_getInstanceSize([NSArray class])
361</pre>
362
363<!-- ======================================================================= -->
Argyrios Kyrtzidis3b5b92a2010-09-13 17:48:07 +0000364<h3 id="objc_objs-cast">Internal Objective-C types</h3>
365<!-- ======================================================================= -->
366
367<p>GCC allows using pointers to internal Objective-C objects, <tt>struct objc_object*</tt>,
368<tt>struct objc_selector*</tt>, and <tt>struct objc_class*</tt> in place of the types
369<tt>id</tt>, <tt>SEL</tt>, and <tt>Class</tt> respectively. Clang treats the
370internal Objective-C structures as implementation detail and won't do implicit conversions:
371
372<pre>
373t.mm:11:2: error: no matching function for call to 'f'
374 f((struct objc_object *)p);
375 ^
376t.mm:5:6: note: candidate function not viable: no known conversion from 'struct objc_object *' to 'id' for 1st argument
377void f(id x);
378 ^
379</pre>
380
381<p>Code should use types <tt>id</tt>, <tt>SEL</tt>, and <tt>Class</tt>
382instead of the internal types.</p>
383
384<!-- ======================================================================= -->
Fariborz Jahanianddfa6c32010-10-22 22:35:51 +0000385<h3 id="c_variables-class">C variables in @class or @protocol</h3>
386<!-- ======================================================================= -->
387
388<p>GCC allows declaration of C variables in a @class or @protocol, but not
389C functions. Clang does not allow variable or C function declarations. External
390declarations, however, is allowed. Variables may only be declared in an
391@implementation.
392
393<pre>
394@interface XX
395int x; // not allowed in clang
396int one=1; // not allowed in clang
397extern int OK;
398@end
399
400</pre>
401
402<!-- ======================================================================= -->
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000403<h2 id="c++">C++ compatibility</h3>
404<!-- ======================================================================= -->
405
406<!-- ======================================================================= -->
407<h3 id="vla">Variable-length arrays</h3>
408<!-- ======================================================================= -->
409
410<p>GCC and C99 allow an array's size to be determined at run
411time. This extension is not permitted in standard C++. However, Clang
412supports such variable length arrays in very limited circumstances for
413compatibility with GNU C and C99 programs:</p>
414
415<ul>
416 <li>The element type of a variable length array must be a POD
417 ("plain old data") type, which means that it cannot have any
418 user-declared constructors or destructors, base classes, or any
419 members if non-POD type. All C types are POD types.</li>
420
421 <li>Variable length arrays cannot be used as the type of a non-type
422template parameter.</li> </ul>
423
424<p>If your code uses variable length arrays in a manner that Clang doesn't support, there are several ways to fix your code:
425
426<ol>
427<li>replace the variable length array with a fixed-size array if you can
428 determine a
429 reasonable upper bound at compile time; sometimes this is as
430 simple as changing <tt>int size = ...;</tt> to <tt>const int size
431 = ...;</tt> (if the definition of <tt>size</tt> is a compile-time
432 integral constant);</li>
433<li>use an <tt>std::string</tt> instead of a <tt>char []</tt>;</li>
434<li>use <tt>std::vector</tt> or some other suitable container type;
435 or</li>
436<li>allocate the array on the heap instead using <tt>new Type[]</tt> -
437 just remember to <tt>delete[]</tt> it.</li>
438</ol>
439
440<!-- ======================================================================= -->
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000441<h3 id="dep_lookup">Unqualified lookup in templates</h3>
442<!-- ======================================================================= -->
443
444<p>Some versions of GCC accept the following invalid code:
445
446<pre>
447template &lt;typename T&gt; T Squared(T x) {
448 return Multiply(x, x);
449}
450
451int Multiply(int x, int y) {
452 return x * y;
453}
454
455int main() {
456 Squared(5);
457}
458</pre>
459
460<p>Clang complains:
461
462<pre> <b>my_file.cpp:2:10: <span class="error">error:</span> use of undeclared identifier 'Multiply'</b>
463 return Multiply(x, x);
464 <span class="caret"> ^</span>
465
466 <b>my_file.cpp:10:3: <span class="note">note:</span> in instantiation of function template specialization 'Squared&lt;int&gt;' requested here</b>
467 Squared(5);
468 <span class="caret"> ^</span>
469</pre>
470
471<p>The C++ standard says that unqualified names like <q>Multiply</q>
472are looked up in two ways.
473
474<p>First, the compiler does <i>unqualified lookup</i> in the scope
475where the name was written. For a template, this means the lookup is
476done at the point where the template is defined, not where it's
477instantiated. Since <tt>Multiply</tt> hasn't been declared yet at
478this point, unqualified lookup won't find it.
479
480<p>Second, if the name is called like a function, then the compiler
481also does <i>argument-dependent lookup</i> (ADL). (Sometimes
482unqualified lookup can suppress ADL; see [basic.lookup.argdep]p3 for
483more information.) In ADL, the compiler looks at the types of all the
484arguments to the call. When it finds a class type, it looks up the
485name in that class's namespace; the result is all the declarations it
486finds in those namespaces, plus the declarations from unqualified
487lookup. However, the compiler doesn't do ADL until it knows all the
488argument types.
489
490<p>In our example, <tt>Multiply</tt> is called with dependent
491arguments, so ADL isn't done until the template is instantiated. At
492that point, the arguments both have type <tt>int</tt>, which doesn't
493contain any class types, and so ADL doesn't look in any namespaces.
494Since neither form of lookup found the declaration
495of <tt>Multiply</tt>, the code doesn't compile.
496
497<p>Here's another example, this time using overloaded operators,
498which obey very similar rules.
499
500<pre>#include &lt;iostream&gt;
501
502template&lt;typename T&gt;
503void Dump(const T&amp; value) {
504 std::cout &lt;&lt; value &lt;&lt; "\n";
505}
506
507namespace ns {
508 struct Data {};
509}
510
511std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, ns::Data data) {
512 return out &lt;&lt; "Some data";
513}
514
515void Use() {
516 Dump(ns::Data());
517}</pre>
518
519<p>Again, Clang complains about not finding a matching function:</p>
520
521<pre>
522<b>my_file.cpp:5:13: <span class="error">error:</span> invalid operands to binary expression ('ostream' (aka 'basic_ostream&lt;char&gt;') and 'ns::Data const')</b>
523 std::cout &lt;&lt; value &lt;&lt; "\n";
524 <span class="caret">~~~~~~~~~ ^ ~~~~~</span>
525<b>my_file.cpp:17:3: <span class="note">note:</span> in instantiation of function template specialization 'Dump&lt;ns::Data&gt;' requested here</b>
526 Dump(ns::Data());
527 <span class="caret">^</span>
528</pre>
529
530<p>Just like before, unqualified lookup didn't find any declarations
531with the name <tt>operator&lt;&lt;</tt>. Unlike before, the argument
532types both contain class types: one of them is an instance of the
533class template type <tt>std::basic_ostream</tt>, and the other is the
534type <tt>ns::Data</tt> that we declared above. Therefore, ADL will
535look in the namespaces <tt>std</tt> and <tt>ns</tt> for
536an <tt>operator&lt;&lt;</tt>. Since one of the argument types was
537still dependent during the template definition, ADL isn't done until
538the template is instantiated during <tt>Use</tt>, which means that
539the <tt>operator&lt;&lt;</tt> we want it to find has already been
540declared. Unfortunately, it was declared in the global namespace, not
541in either of the namespaces that ADL will look in!
542
543<p>There are two ways to fix this problem:</p>
544<ol><li>Make sure the function you want to call is declared before the
545template that might call it. This is the only option if none of its
546argument types contain classes. You can do this either by moving the
547template definition, or by moving the function definition, or by
548adding a forward declaration of the function before the template.</li>
549<li>Move the function into the same namespace as one of its arguments
550so that ADL applies.</li></ol>
551
552<p>For more information about argument-dependent lookup, see
553[basic.lookup.argdep]. For more information about the ordering of
554lookup in templates, see [temp.dep.candidate].
555
556<!-- ======================================================================= -->
557<h3 id="dep_lookup_bases">Unqualified lookup into dependent bases of class templates</h3>
558<!-- ======================================================================= -->
559
560Some versions of GCC accept the following invalid code:
561
562<pre>
563template &lt;typename T&gt; struct Base {
564 void DoThis(T x) {}
565 static void DoThat(T x) {}
566};
567
568template &lt;typename T&gt; struct Derived : public Base&lt;T&gt; {
569 void Work(T x) {
570 DoThis(x); // Invalid!
571 DoThat(x); // Invalid!
572 }
573};
574</pre>
575
576Clang correctly rejects it with the following errors
577(when <tt>Derived</tt> is eventually instantiated):
578
579<pre>
580my_file.cpp:8:5: error: use of undeclared identifier 'DoThis'
581 DoThis(x);
582 ^
583 this-&gt;
584my_file.cpp:2:8: note: must qualify identifier to find this declaration in dependent base class
585 void DoThis(T x) {}
586 ^
587my_file.cpp:9:5: error: use of undeclared identifier 'DoThat'
588 DoThat(x);
589 ^
590 this-&gt;
591my_file.cpp:3:15: note: must qualify identifier to find this declaration in dependent base class
592 static void DoThat(T x) {}
593</pre>
594
595Like we said <a href="#dep_lookup">above</a>, unqualified names like
596<tt>DoThis</tt> and <tt>DoThat</tt> are looked up when the template
597<tt>Derived</tt> is defined, not when it's instantiated. When we look
598up a name used in a class, we usually look into the base classes.
599However, we can't look into the base class <tt>Base&lt;T&gt;</tt>
600because its type depends on the template argument <tt>T</tt>, so the
601standard says we should just ignore it. See [temp.dep]p3 for details.
602
603<p>The fix, as Clang tells you, is to tell the compiler that we want a
604class member by prefixing the calls with <tt>this-&gt;</tt>:
605
606<pre>
607 void Work(T x) {
608 <b>this-&gt;</b>DoThis(x);
609 <b>this-&gt;</b>DoThat(x);
610 }
611</pre>
612
613Alternatively, you can tell the compiler exactly where to look:
614
615<pre>
616 void Work(T x) {
617 <b>Base&lt;T&gt;</b>::DoThis(x);
618 <b>Base&lt;T&gt;</b>::DoThat(x);
619 }
620</pre>
621
622This works whether the methods are static or not, but be careful:
623if <tt>DoThis</tt> is virtual, calling it this way will bypass virtual
624dispatch!
625
626<!-- ======================================================================= -->
627<h3 id="undep_incomplete">Incomplete types in templates</h3>
628<!-- ======================================================================= -->
629
630The following code is invalid, but compilers are allowed to accept it:
631
632<pre>
633 class IOOptions;
634 template &lt;class T&gt; bool read(T &amp;value) {
635 IOOptions opts;
636 return read(opts, value);
637 }
638
639 class IOOptions { bool ForceReads; };
640 bool read(const IOOptions &amp;opts, int &amp;x);
641 template bool read&lt;&gt;(int &amp;);
642</pre>
643
644The standard says that types which don't depend on template parameters
645must be complete when a template is defined if they affect the
646program's behavior. However, the standard also says that compilers
647are free to not enforce this rule. Most compilers enforce it to some
648extent; for example, it would be an error in GCC to
649write <tt>opts.ForceReads</tt> in the code above. In Clang, we feel
650that enforcing the rule consistently lets us provide a better
651experience, but unfortunately it also means we reject some code that
652other compilers accept.
653
654<p>We've explained the rule here in very imprecise terms; see
655[temp.res]p8 for details.
656
657<!-- ======================================================================= -->
658<h3 id="bad_templates">Templates with no valid instantiations</h3>
659<!-- ======================================================================= -->
660
661The following code contains a typo: the programmer
662meant <tt>init()</tt> but wrote <tt>innit()</tt> instead.
663
664<pre>
665 template &lt;class T&gt; class Processor {
666 ...
667 void init();
668 ...
669 };
670 ...
671 template &lt;class T&gt; void process() {
672 Processor&lt;T&gt; processor;
673 processor.innit(); // <-- should be 'init()'
674 ...
675 }
676</pre>
677
678Unfortunately, we can't flag this mistake as soon as we see it: inside
679a template, we're not allowed to make assumptions about "dependent
680types" like <tt>Processor&lt;T&gt;</tt>. Suppose that later on in
681this file the programmer adds an explicit specialization
682of <tt>Processor</tt>, like so:
683
684<pre>
685 template &lt;&gt; class Processor&lt;char*&gt; {
686 void innit();
687 };
688</pre>
689
690Now the program will work &mdash; as long as the programmer only ever
691instantiates <tt>process()</tt> with <tt>T = char*</tt>! This is why
692it's hard, and sometimes impossible, to diagnose mistakes in a
693template definition before it's instantiated.
694
695<p>The standard says that a template with no valid instantiations is
696ill-formed. Clang tries to do as much checking as possible at
697definition-time instead of instantiation-time: not only does this
698produce clearer diagnostics, but it also substantially improves
699compile times when using pre-compiled headers. The downside to this
700philosophy is that Clang sometimes fails to process files because they
701contain broken templates that are no longer used. The solution is
702simple: since the code is unused, just remove it.
703
704<!-- ======================================================================= -->
705<h3 id="default_init_const">Default initialization of const variable of a class type requires user-defined default constructor</h3>
706<!-- ======================================================================= -->
707
708If a <tt>class</tt> or <tt>struct</tt> has no user-defined default
709constructor, C++ doesn't allow you to default construct a <tt>const</tt>
710instance of it like this ([dcl.init], p9):
711
712<pre>
713class Foo {
714 public:
715 // The compiler-supplied default constructor works fine, so we
716 // don't bother with defining one.
717 ...
718};
719
720void Bar() {
721 const Foo foo; // Error!
722 ...
723}
724</pre>
725
726To fix this, you can define a default constructor for the class:
727
728<pre>
729class Foo {
730 public:
731 Foo() {}
732 ...
733};
734
735void Bar() {
736 const Foo foo; // Now the compiler is happy.
737 ...
738}
739</pre>
740
741<!-- ======================================================================= -->
Douglas Gregora66d3bb2010-11-10 20:24:21 +0000742<h3 id="param_name_lookup">Parameter name lookup</h3>
743<!-- ======================================================================= -->
744
745<p>Due to a bug in its implementation, GCC allows the redeclaration of function parameter names within a function prototype in C++ code, e.g.</p>
746<blockquote>
747<pre>
748void f(int a, int a);
749</pre>
750</blockquote>
751<p>Clang diagnoses this error (where the parameter name has been redeclared). To fix this problem, rename one of the parameters.</p>
752
753<!-- ======================================================================= -->
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000754<h2 id="objective-c++">Objective-C++ compatibility</h3>
755<!-- ======================================================================= -->
756
757<!-- ======================================================================= -->
758<h3 id="implicit-downcasts">Implicit downcasts</h3>
759<!-- ======================================================================= -->
760
761<p>Due to a bug in its implementation, GCC allows implicit downcasts
762(from base class to a derived class) when calling functions. Such code is
763inherently unsafe, since the object might not actually be an instance
764of the derived class, and is rejected by Clang. For example, given
765this code:</p>
766
767<pre>
768@interface Base @end
769@interface Derived : Base @end
770
771void f(Derived *);
772void g(Base *base) {
773 f(base);
774}
775</pre>
776
777<p>Clang produces the following error:</p>
778
779<pre>
780downcast.mm:6:3: error: no matching function for call to 'f'
781 f(base);
782 ^
Douglas Gregor92bc0272010-07-01 03:50:01 +0000783downcast.mm:4:6: note: candidate function not viable: cannot convert from
784 superclass 'Base *' to subclass 'Derived *' for 1st argument
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000785void f(Derived *);
786 ^
787</pre>
788
789<p>If the downcast is actually correct (e.g., because the code has
790already checked that the object has the appropriate type), add an
791explicit cast:</p>
792
793<pre>
794 f((Derived *)base);
795</pre>
796
Fariborz Jahanian36e738a2010-08-11 18:57:26 +0000797<!-- ======================================================================= -->
798<h3 id="Use of class as method name">Use of class as method name</h3>
799<!-- ======================================================================= -->
800
801<p>Use of 'class' name to declare a method is allowed in objective-c++ mode to
802be compatible with GCC. However, use of property dot syntax notation to call
803this method is not allowed in clang++, as [I class] is a suitable syntax that
804will work. So, this test will fail in clang++.
805
806<pre>
807@interface I {
808int cls;
809}
810+ (int)class;
811@end
812
813@implementation I
814- (int) Meth { return I.class; }
815@end
816<pre>
817
818
Douglas Gregorc41b6ff2010-06-30 22:01:08 +0000819</div>
820</body>
821</html>