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