]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - www/compatibility.html
Update clang to r108243.
[FreeBSD/FreeBSD.git] / www / compatibility.html
1 <!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>
35       <li><a href="#lvalue-cast">Lvalue casts</a></li>
36     </ul>
37   </li>
38   <li><a href="#objective-c">Objective-C compatibility</a>
39     <ul>
40       <li><a href="#super-cast">Cast of super</a></li>
41       <li><a href="#sizeof-interface">Size of interfaces</a></li>
42     </ul>
43   </li>
44   <li><a href="#c++">C++ compatibility</a>
45     <ul>
46       <li><a href="#vla">Variable-length arrays</a></li>
47       <li><a href="#init_static_const">Initialization of non-integral static const data members within a class definition</a></li>
48       <li><a href="#dep_lookup">Unqualified lookup in templates</a></li>
49       <li><a href="#dep_lookup_bases">Unqualified lookup into dependent bases of class templates</a></li>
50       <li><a href="#undep_incomplete">Incomplete types in templates</a></li>
51       <li><a href="#bad_templates">Templates with no valid instantiations</a></li>
52       <li><a href="#default_init_const">Default initialization of const
53       variable of a class type requires user-defined default
54       constructor</a></li>
55     </ul>
56   </li>
57   <li><a href="#objective-c++">Objective-C++ compatibility</a>
58     <ul>
59       <li><a href="#implicit-downcasts">Implicit downcasts</a></li>
60     </ul>
61   </li>
62 </ul>
63
64 <!-- ======================================================================= -->
65 <h2 id="c">C compatibility</h3>
66 <!-- ======================================================================= -->
67
68 <!-- ======================================================================= -->
69 <h3 id="inline">C99 inline functions</h3>
70 <!-- ======================================================================= -->
71 <p>By default, Clang builds C code according to the C99 standard,
72 which provides different inlining semantics than GCC's default
73 behavior. For example, when compiling the following code with no optimization:</p>
74 <pre>
75 inline int add(int i, int j) { return i + j; }
76
77 int main() {
78   int i = add(4, 5);
79   return i;
80 }
81 </pre>
82
83 <p>In C99, this is an incomplete (incorrect) program because there is
84 no external definition of the <code>add</code> function: the inline
85 definition is only used for optimization, if the compiler decides to
86 perform inlining. Therefore, we will get a (correct) link-time error
87 with Clang, e.g.:</p>
88
89 <pre>
90 Undefined symbols:
91   "_add", referenced from:
92       _main in cc-y1jXIr.o
93 </pre>
94
95 <p>There are several ways to fix this problem:</p>
96
97 <ul>
98   <li>Change <code>add</code> to a <code>static inline</code>
99   function. Static inline functions are always resolved within the
100   translation unit, so you won't have to add an external, non-inline
101   definition of the function elsewhere in your program.</li>
102   
103   <li>Provide an external (non-inline) definition of <code>add</code>
104   somewhere in your program.</li>
105    
106   <li>Compile with the GNU89 dialect by adding
107   <code>-std=gnu89</code> to the set of Clang options. This option is
108   only recommended if the program source cannot be changed or if the
109   program also relies on additional C89-specific behavior that cannot
110   be changed.</li>
111 </ul>
112
113 <!-- ======================================================================= -->
114 <h3 id="lvalue-cast">Lvalue casts</h3>
115 <!-- ======================================================================= -->
116
117 <p>Old versions of GCC permit casting the left-hand side of an assignment to a
118 different type. Clang produces an error on similar code, e.g.,</p>
119
120 <pre>
121 lvalue.c:2:3: error: assignment to cast is illegal, lvalue casts are not
122       supported
123   (int*)addr = val;
124   ^~~~~~~~~~ ~
125 </pre>
126
127 <p>To fix this problem, move the cast to the right-hand side. In this
128 example, one could use:</p>
129
130 <pre>
131   addr = (float *)val;
132 </pre>
133
134 <!-- ======================================================================= -->
135 <h2 id="objective-c">Objective-C compatibility</h3>
136 <!-- ======================================================================= -->
137
138 <!-- ======================================================================= -->
139 <h3 id="super-cast">Cast of super</h3>
140 <!-- ======================================================================= -->
141
142 <p>GCC treats the <code>super</code> identifier as an expression that
143 can, among other things, be cast to a different type. Clang treats
144 <code>super</code> as a context-sensitive keyword, and will reject a
145 type-cast of <code>super</code>:</p>
146
147 <pre>
148 super.m:11:12: error: cannot cast 'super' (it isn't an expression)
149   [(Super*)super add:4];
150    ~~~~~~~~^
151 </pre>
152
153 <p>To fix this problem, remove the type cast, e.g.</p>
154 <pre>
155   [super add:4];
156 </pre>
157
158 <!-- ======================================================================= -->
159 <h3 id="sizeof-interface">Size of interfaces</h3>
160 <!-- ======================================================================= -->
161
162 <p>When using the "non-fragile" Objective-C ABI in use, the size of an
163 Objective-C class may change over time as instance variables are added
164 (or removed). For this reason, Clang rejects the application of the
165 <code>sizeof</code> operator to an Objective-C class when using this
166 ABI:</p>
167
168 <pre>
169 sizeof.m:4:14: error: invalid application of 'sizeof' to interface 'NSArray' in
170       non-fragile ABI
171   int size = sizeof(NSArray);
172              ^     ~~~~~~~~~
173 </pre>
174
175 <p>Code that relies on the size of an Objective-C class is likely to
176 be broken anyway, since that size is not actually constant. To address
177 this problem, use the Objective-C runtime API function
178 <code>class_getInstanceSize()</code>:</p>
179
180 <pre>
181   class_getInstanceSize([NSArray class])
182 </pre>
183
184 <!-- ======================================================================= -->
185 <h2 id="c++">C++ compatibility</h3>
186 <!-- ======================================================================= -->
187
188 <!-- ======================================================================= -->
189 <h3 id="vla">Variable-length arrays</h3>
190 <!-- ======================================================================= -->
191
192 <p>GCC and C99 allow an array's size to be determined at run
193 time. This extension is not permitted in standard C++. However, Clang
194 supports such variable length arrays in very limited circumstances for
195 compatibility with GNU C and C99 programs:</p>
196
197 <ul>  
198   <li>The element type of a variable length array must be a POD
199   ("plain old data") type, which means that it cannot have any
200   user-declared constructors or destructors, base classes, or any
201   members if non-POD type. All C types are POD types.</li>
202
203   <li>Variable length arrays cannot be used as the type of a non-type
204 template parameter.</li> </ul>
205
206 <p>If your code uses variable length arrays in a manner that Clang doesn't support, there are several ways to fix your code:
207
208 <ol>
209 <li>replace the variable length array with a fixed-size array if you can
210     determine a
211     reasonable upper bound at compile time; sometimes this is as
212     simple as changing <tt>int size = ...;</tt> to <tt>const int size
213     = ...;</tt> (if the definition of <tt>size</tt> is a compile-time
214     integral constant);</li>
215 <li>use an <tt>std::string</tt> instead of a <tt>char []</tt>;</li>
216 <li>use <tt>std::vector</tt> or some other suitable container type;
217     or</li>
218 <li>allocate the array on the heap instead using <tt>new Type[]</tt> -
219     just remember to <tt>delete[]</tt> it.</li>
220 </ol>
221
222 <!-- ======================================================================= -->
223 <h3 id="init_static_const">Initialization of non-integral static const data members within a class definition</h3>
224 <!-- ======================================================================= -->
225
226 The following code is ill-formed in C++'03:
227
228 <pre>
229 class SomeClass {
230  public:
231   static const double SomeConstant = 0.5;
232 };
233
234 const double SomeClass::SomeConstant;
235 </pre>
236
237 Clang errors with something similar to:
238
239 <pre>
240 .../your_file.h:42:42: error: 'SomeConstant' can only be initialized if it is a static const integral data member
241   static const double SomeConstant = 0.5;
242                       ^              ~~~
243 </pre>
244
245 Only <i>integral</i> constant expressions are allowed as initializers
246 within the class definition. See C++'03 [class.static.data] p4 for the
247 details of this restriction.  The fix here is straightforward: move
248 the initializer to the definition of the static data member, which
249 must exist outside of the class definition:
250
251 <pre>
252 class SomeClass {
253  public:
254   static const double SomeConstant;
255 };
256
257 const double SomeClass::SomeConstant<b> = 0.5</b>;
258 </pre>
259
260 Note that the forthcoming C++0x standard will allow this.
261
262 <!-- ======================================================================= -->
263 <h3 id="dep_lookup">Unqualified lookup in templates</h3>
264 <!-- ======================================================================= -->
265
266 <p>Some versions of GCC accept the following invalid code:
267
268 <pre>
269 template &lt;typename T&gt; T Squared(T x) {
270   return Multiply(x, x);
271 }
272
273 int Multiply(int x, int y) {
274   return x * y;
275 }
276
277 int main() {
278   Squared(5);
279 }
280 </pre>
281
282 <p>Clang complains:
283
284 <pre>  <b>my_file.cpp:2:10: <span class="error">error:</span> use of undeclared identifier 'Multiply'</b>
285     return Multiply(x, x);
286   <span class="caret">         ^</span>
287
288   <b>my_file.cpp:10:3: <span class="note">note:</span> in instantiation of function template specialization 'Squared&lt;int&gt;' requested here</b>
289     Squared(5);
290   <span class="caret">  ^</span>
291 </pre>
292
293 <p>The C++ standard says that unqualified names like <q>Multiply</q>
294 are looked up in two ways.
295
296 <p>First, the compiler does <i>unqualified lookup</i> in the scope
297 where the name was written.  For a template, this means the lookup is
298 done at the point where the template is defined, not where it's
299 instantiated.  Since <tt>Multiply</tt> hasn't been declared yet at
300 this point, unqualified lookup won't find it.
301
302 <p>Second, if the name is called like a function, then the compiler
303 also does <i>argument-dependent lookup</i> (ADL).  (Sometimes
304 unqualified lookup can suppress ADL; see [basic.lookup.argdep]p3 for
305 more information.)  In ADL, the compiler looks at the types of all the
306 arguments to the call.  When it finds a class type, it looks up the
307 name in that class's namespace; the result is all the declarations it
308 finds in those namespaces, plus the declarations from unqualified
309 lookup.  However, the compiler doesn't do ADL until it knows all the
310 argument types.
311
312 <p>In our example, <tt>Multiply</tt> is called with dependent
313 arguments, so ADL isn't done until the template is instantiated.  At
314 that point, the arguments both have type <tt>int</tt>, which doesn't
315 contain any class types, and so ADL doesn't look in any namespaces.
316 Since neither form of lookup found the declaration
317 of <tt>Multiply</tt>, the code doesn't compile.
318
319 <p>Here's another example, this time using overloaded operators,
320 which obey very similar rules.
321
322 <pre>#include &lt;iostream&gt;
323
324 template&lt;typename T&gt;
325 void Dump(const T&amp; value) {
326   std::cout &lt;&lt; value &lt;&lt; "\n";
327 }
328
329 namespace ns {
330   struct Data {};
331 }
332
333 std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, ns::Data data) {
334   return out &lt;&lt; "Some data";
335 }
336
337 void Use() {
338   Dump(ns::Data());
339 }</pre>
340
341 <p>Again, Clang complains about not finding a matching function:</p>
342
343 <pre>
344 <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>
345   std::cout &lt;&lt; value &lt;&lt; "\n";
346   <span class="caret">~~~~~~~~~ ^  ~~~~~</span>
347 <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>
348   Dump(ns::Data());
349   <span class="caret">^</span>
350 </pre>
351
352 <p>Just like before, unqualified lookup didn't find any declarations
353 with the name <tt>operator&lt;&lt;</tt>.  Unlike before, the argument
354 types both contain class types: one of them is an instance of the
355 class template type <tt>std::basic_ostream</tt>, and the other is the
356 type <tt>ns::Data</tt> that we declared above.  Therefore, ADL will
357 look in the namespaces <tt>std</tt> and <tt>ns</tt> for
358 an <tt>operator&lt;&lt;</tt>.  Since one of the argument types was
359 still dependent during the template definition, ADL isn't done until
360 the template is instantiated during <tt>Use</tt>, which means that
361 the <tt>operator&lt;&lt;</tt> we want it to find has already been
362 declared.  Unfortunately, it was declared in the global namespace, not
363 in either of the namespaces that ADL will look in!
364
365 <p>There are two ways to fix this problem:</p>
366 <ol><li>Make sure the function you want to call is declared before the
367 template that might call it.  This is the only option if none of its
368 argument types contain classes.  You can do this either by moving the
369 template definition, or by moving the function definition, or by
370 adding a forward declaration of the function before the template.</li>
371 <li>Move the function into the same namespace as one of its arguments
372 so that ADL applies.</li></ol>
373
374 <p>For more information about argument-dependent lookup, see
375 [basic.lookup.argdep].  For more information about the ordering of
376 lookup in templates, see [temp.dep.candidate].
377
378 <!-- ======================================================================= -->
379 <h3 id="dep_lookup_bases">Unqualified lookup into dependent bases of class templates</h3>
380 <!-- ======================================================================= -->
381
382 Some versions of GCC accept the following invalid code:
383
384 <pre>
385 template &lt;typename T&gt; struct Base {
386   void DoThis(T x) {}
387   static void DoThat(T x) {}
388 };
389
390 template &lt;typename T&gt; struct Derived : public Base&lt;T&gt; {
391   void Work(T x) {
392     DoThis(x);  // Invalid!
393     DoThat(x);  // Invalid!
394   }
395 };
396 </pre>
397
398 Clang correctly rejects it with the following errors
399 (when <tt>Derived</tt> is eventually instantiated):
400
401 <pre>
402 my_file.cpp:8:5: error: use of undeclared identifier 'DoThis'
403     DoThis(x);
404     ^
405     this-&gt;
406 my_file.cpp:2:8: note: must qualify identifier to find this declaration in dependent base class
407   void DoThis(T x) {}
408        ^
409 my_file.cpp:9:5: error: use of undeclared identifier 'DoThat'
410     DoThat(x);
411     ^
412     this-&gt;
413 my_file.cpp:3:15: note: must qualify identifier to find this declaration in dependent base class
414   static void DoThat(T x) {}
415 </pre>
416
417 Like we said <a href="#dep_lookup">above</a>, unqualified names like
418 <tt>DoThis</tt> and <tt>DoThat</tt> are looked up when the template
419 <tt>Derived</tt> is defined, not when it's instantiated.  When we look
420 up a name used in a class, we usually look into the base classes.
421 However, we can't look into the base class <tt>Base&lt;T&gt;</tt>
422 because its type depends on the template argument <tt>T</tt>, so the
423 standard says we should just ignore it.  See [temp.dep]p3 for details.
424
425 <p>The fix, as Clang tells you, is to tell the compiler that we want a
426 class member by prefixing the calls with <tt>this-&gt;</tt>:
427
428 <pre>
429   void Work(T x) {
430     <b>this-&gt;</b>DoThis(x);
431     <b>this-&gt;</b>DoThat(x);
432   }
433 </pre>
434
435 Alternatively, you can tell the compiler exactly where to look:
436
437 <pre>
438   void Work(T x) {
439     <b>Base&lt;T&gt;</b>::DoThis(x);
440     <b>Base&lt;T&gt;</b>::DoThat(x);
441   }
442 </pre>
443
444 This works whether the methods are static or not, but be careful:
445 if <tt>DoThis</tt> is virtual, calling it this way will bypass virtual
446 dispatch!
447
448 <!-- ======================================================================= -->
449 <h3 id="undep_incomplete">Incomplete types in templates</h3>
450 <!-- ======================================================================= -->
451
452 The following code is invalid, but compilers are allowed to accept it:
453
454 <pre>
455   class IOOptions;
456   template &lt;class T&gt; bool read(T &amp;value) {
457     IOOptions opts;
458     return read(opts, value);
459   }
460
461   class IOOptions { bool ForceReads; };
462   bool read(const IOOptions &amp;opts, int &amp;x);
463   template bool read&lt;&gt;(int &amp;);
464 </pre>
465
466 The standard says that types which don't depend on template parameters
467 must be complete when a template is defined if they affect the
468 program's behavior.  However, the standard also says that compilers
469 are free to not enforce this rule.  Most compilers enforce it to some
470 extent; for example, it would be an error in GCC to
471 write <tt>opts.ForceReads</tt> in the code above.  In Clang, we feel
472 that enforcing the rule consistently lets us provide a better
473 experience, but unfortunately it also means we reject some code that
474 other compilers accept.
475
476 <p>We've explained the rule here in very imprecise terms; see
477 [temp.res]p8 for details.
478
479 <!-- ======================================================================= -->
480 <h3 id="bad_templates">Templates with no valid instantiations</h3>
481 <!-- ======================================================================= -->
482
483 The following code contains a typo: the programmer
484 meant <tt>init()</tt> but wrote <tt>innit()</tt> instead.
485
486 <pre>
487   template &lt;class T&gt; class Processor {
488     ...
489     void init();
490     ...
491   };
492   ...
493   template &lt;class T&gt; void process() {
494     Processor&lt;T&gt; processor;
495     processor.innit();       // <-- should be 'init()'
496     ...
497   }
498 </pre>
499
500 Unfortunately, we can't flag this mistake as soon as we see it: inside
501 a template, we're not allowed to make assumptions about "dependent
502 types" like <tt>Processor&lt;T&gt;</tt>.  Suppose that later on in
503 this file the programmer adds an explicit specialization
504 of <tt>Processor</tt>, like so:
505
506 <pre>
507   template &lt;&gt; class Processor&lt;char*&gt; {
508     void innit();
509   };
510 </pre>
511
512 Now the program will work &mdash; as long as the programmer only ever
513 instantiates <tt>process()</tt> with <tt>T = char*</tt>!  This is why
514 it's hard, and sometimes impossible, to diagnose mistakes in a
515 template definition before it's instantiated.
516
517 <p>The standard says that a template with no valid instantiations is
518 ill-formed.  Clang tries to do as much checking as possible at
519 definition-time instead of instantiation-time: not only does this
520 produce clearer diagnostics, but it also substantially improves
521 compile times when using pre-compiled headers.  The downside to this
522 philosophy is that Clang sometimes fails to process files because they
523 contain broken templates that are no longer used.  The solution is
524 simple: since the code is unused, just remove it.
525
526 <!-- ======================================================================= -->
527 <h3 id="default_init_const">Default initialization of const variable of a class type requires user-defined default constructor</h3>
528 <!-- ======================================================================= -->
529
530 If a <tt>class</tt> or <tt>struct</tt> has no user-defined default
531 constructor, C++ doesn't allow you to default construct a <tt>const</tt>
532 instance of it like this ([dcl.init], p9):
533
534 <pre>
535 class Foo {
536  public:
537   // The compiler-supplied default constructor works fine, so we
538   // don't bother with defining one.
539   ...
540 };
541
542 void Bar() {
543   const Foo foo;  // Error!
544   ...
545 }
546 </pre>
547
548 To fix this, you can define a default constructor for the class:
549
550 <pre>
551 class Foo {
552  public:
553   Foo() {}
554   ...
555 };
556
557 void Bar() {
558   const Foo foo;  // Now the compiler is happy.
559   ...
560 }
561 </pre>
562
563 <!-- ======================================================================= -->
564 <h2 id="objective-c++">Objective-C++ compatibility</h3>
565 <!-- ======================================================================= -->
566
567 <!-- ======================================================================= -->
568 <h3 id="implicit-downcasts">Implicit downcasts</h3>
569 <!-- ======================================================================= -->
570
571 <p>Due to a bug in its implementation, GCC allows implicit downcasts
572 (from base class to a derived class) when calling functions. Such code is
573 inherently unsafe, since the object might not actually be an instance
574 of the derived class, and is rejected by Clang. For example, given
575 this code:</p>
576
577 <pre>
578 @interface Base @end
579 @interface Derived : Base @end
580
581 void f(Derived *);
582 void g(Base *base) {
583   f(base);
584 }
585 </pre>
586
587 <p>Clang produces the following error:</p>
588
589 <pre>
590 downcast.mm:6:3: error: no matching function for call to 'f'
591   f(base);
592   ^
593 downcast.mm:4:6: note: candidate function not viable: cannot convert from
594       superclass 'Base *' to subclass 'Derived *' for 1st argument
595 void f(Derived *);
596      ^
597 </pre>
598
599 <p>If the downcast is actually correct (e.g., because the code has
600 already checked that the object has the appropriate type), add an
601 explicit cast:</p>
602
603 <pre>
604   f((Derived *)base);
605 </pre>
606
607 </div>
608 </body>
609 </html>