1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
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">
14 <!--#include virtual="menu.html.incl"-->
18 <!-- ======================================================================= -->
19 <h1>Language Compatibility</h1>
20 <!-- ======================================================================= -->
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>
32 <li><a href="#c">C compatibility</a>
34 <li><a href="#inline">C99 inline functions</a></li>
35 <li><a href="#lvalue-cast">Lvalue casts</a></li>
38 <li><a href="#objective-c">Objective-C compatibility</a>
40 <li><a href="#super-cast">Cast of super</a></li>
41 <li><a href="#sizeof-interface">Size of interfaces</a></li>
44 <li><a href="#c++">C++ compatibility</a>
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
57 <li><a href="#objective-c++">Objective-C++ compatibility</a>
59 <li><a href="#implicit-downcasts">Implicit downcasts</a></li>
64 <!-- ======================================================================= -->
65 <h2 id="c">C compatibility</h3>
66 <!-- ======================================================================= -->
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>
75 inline int add(int i, int j) { return i + j; }
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
91 "_add", referenced from:
95 <p>There are several ways to fix this problem:</p>
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>
103 <li>Provide an external (non-inline) definition of <code>add</code>
104 somewhere in your program.</li>
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
113 <!-- ======================================================================= -->
114 <h3 id="lvalue-cast">Lvalue casts</h3>
115 <!-- ======================================================================= -->
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>
121 lvalue.c:2:3: error: assignment to cast is illegal, lvalue casts are not
127 <p>To fix this problem, move the cast to the right-hand side. In this
128 example, one could use:</p>
134 <!-- ======================================================================= -->
135 <h2 id="objective-c">Objective-C compatibility</h3>
136 <!-- ======================================================================= -->
138 <!-- ======================================================================= -->
139 <h3 id="super-cast">Cast of super</h3>
140 <!-- ======================================================================= -->
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>
148 super.m:11:12: error: cannot cast 'super' (it isn't an expression)
149 [(Super*)super add:4];
153 <p>To fix this problem, remove the type cast, e.g.</p>
158 <!-- ======================================================================= -->
159 <h3 id="sizeof-interface">Size of interfaces</h3>
160 <!-- ======================================================================= -->
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
169 sizeof.m:4:14: error: invalid application of 'sizeof' to interface 'NSArray' in
171 int size = sizeof(NSArray);
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>
181 class_getInstanceSize([NSArray class])
184 <!-- ======================================================================= -->
185 <h2 id="c++">C++ compatibility</h3>
186 <!-- ======================================================================= -->
188 <!-- ======================================================================= -->
189 <h3 id="vla">Variable-length arrays</h3>
190 <!-- ======================================================================= -->
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>
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>
203 <li>Variable length arrays cannot be used as the type of a non-type
204 template parameter.</li> </ul>
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:
209 <li>replace the variable length array with a fixed-size array if you can
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;
218 <li>allocate the array on the heap instead using <tt>new Type[]</tt> -
219 just remember to <tt>delete[]</tt> it.</li>
222 <!-- ======================================================================= -->
223 <h3 id="init_static_const">Initialization of non-integral static const data members within a class definition</h3>
224 <!-- ======================================================================= -->
226 The following code is ill-formed in C++'03:
231 static const double SomeConstant = 0.5;
234 const double SomeClass::SomeConstant;
237 Clang errors with something similar to:
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;
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:
254 static const double SomeConstant;
257 const double SomeClass::SomeConstant<b> = 0.5</b>;
260 Note that the forthcoming C++0x standard will allow this.
262 <!-- ======================================================================= -->
263 <h3 id="dep_lookup">Unqualified lookup in templates</h3>
264 <!-- ======================================================================= -->
266 <p>Some versions of GCC accept the following invalid code:
269 template <typename T> T Squared(T x) {
270 return Multiply(x, x);
273 int Multiply(int x, int y) {
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>
288 <b>my_file.cpp:10:3: <span class="note">note:</span> in instantiation of function template specialization 'Squared<int>' requested here</b>
290 <span class="caret"> ^</span>
293 <p>The C++ standard says that unqualified names like <q>Multiply</q>
294 are looked up in two ways.
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.
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
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.
319 <p>Here's another example, this time using overloaded operators,
320 which obey very similar rules.
322 <pre>#include <iostream>
324 template<typename T>
325 void Dump(const T& value) {
326 std::cout << value << "\n";
333 std::ostream& operator<<(std::ostream& out, ns::Data data) {
334 return out << "Some data";
341 <p>Again, Clang complains about not finding a matching function:</p>
344 <b>my_file.cpp:5:13: <span class="error">error:</span> invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ns::Data const')</b>
345 std::cout << value << "\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<ns::Data>' requested here</b>
349 <span class="caret">^</span>
352 <p>Just like before, unqualified lookup didn't find any declarations
353 with the name <tt>operator<<</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<<</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<<</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!
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>
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].
378 <!-- ======================================================================= -->
379 <h3 id="dep_lookup_bases">Unqualified lookup into dependent bases of class templates</h3>
380 <!-- ======================================================================= -->
382 Some versions of GCC accept the following invalid code:
385 template <typename T> struct Base {
387 static void DoThat(T x) {}
390 template <typename T> struct Derived : public Base<T> {
392 DoThis(x); // Invalid!
393 DoThat(x); // Invalid!
398 Clang correctly rejects it with the following errors
399 (when <tt>Derived</tt> is eventually instantiated):
402 my_file.cpp:8:5: error: use of undeclared identifier 'DoThis'
406 my_file.cpp:2:8: note: must qualify identifier to find this declaration in dependent base class
409 my_file.cpp:9:5: error: use of undeclared identifier 'DoThat'
413 my_file.cpp:3:15: note: must qualify identifier to find this declaration in dependent base class
414 static void DoThat(T x) {}
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<T></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.
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-></tt>:
430 <b>this-></b>DoThis(x);
431 <b>this-></b>DoThat(x);
435 Alternatively, you can tell the compiler exactly where to look:
439 <b>Base<T></b>::DoThis(x);
440 <b>Base<T></b>::DoThat(x);
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
448 <!-- ======================================================================= -->
449 <h3 id="undep_incomplete">Incomplete types in templates</h3>
450 <!-- ======================================================================= -->
452 The following code is invalid, but compilers are allowed to accept it:
456 template <class T> bool read(T &value) {
458 return read(opts, value);
461 class IOOptions { bool ForceReads; };
462 bool read(const IOOptions &opts, int &x);
463 template bool read<>(int &);
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.
476 <p>We've explained the rule here in very imprecise terms; see
477 [temp.res]p8 for details.
479 <!-- ======================================================================= -->
480 <h3 id="bad_templates">Templates with no valid instantiations</h3>
481 <!-- ======================================================================= -->
483 The following code contains a typo: the programmer
484 meant <tt>init()</tt> but wrote <tt>innit()</tt> instead.
487 template <class T> class Processor {
493 template <class T> void process() {
494 Processor<T> processor;
495 processor.innit(); // <-- should be 'init()'
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<T></tt>. Suppose that later on in
503 this file the programmer adds an explicit specialization
504 of <tt>Processor</tt>, like so:
507 template <> class Processor<char*> {
512 Now the program will work — 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.
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.
526 <!-- ======================================================================= -->
527 <h3 id="default_init_const">Default initialization of const variable of a class type requires user-defined default constructor</h3>
528 <!-- ======================================================================= -->
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):
537 // The compiler-supplied default constructor works fine, so we
538 // don't bother with defining one.
543 const Foo foo; // Error!
548 To fix this, you can define a default constructor for the class:
558 const Foo foo; // Now the compiler is happy.
563 <!-- ======================================================================= -->
564 <h2 id="objective-c++">Objective-C++ compatibility</h3>
565 <!-- ======================================================================= -->
567 <!-- ======================================================================= -->
568 <h3 id="implicit-downcasts">Implicit downcasts</h3>
569 <!-- ======================================================================= -->
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
579 @interface Derived : Base @end
587 <p>Clang produces the following error:</p>
590 downcast.mm:6:3: error: no matching function for call to 'f'
593 downcast.mm:4:6: note: candidate function not viable: cannot convert from
594 superclass 'Base *' to subclass 'Derived *' for 1st argument
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