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