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>
36 <li><a href="#blocks-in-protected-scope">Jumps to within <tt>__block</tt> variable scope</a></li>
39 <li><a href="#objective-c">Objective-C compatibility</a>
41 <li><a href="#super-cast">Cast of super</a></li>
42 <li><a href="#sizeof-interface">Size of interfaces</a></li>
45 <li><a href="#c++">C++ compatibility</a>
47 <li><a href="#vla">Variable-length arrays</a></li>
48 <li><a href="#init_static_const">Initialization of non-integral static const data members within a class definition</a></li>
49 <li><a href="#dep_lookup">Unqualified lookup in templates</a></li>
50 <li><a href="#dep_lookup_bases">Unqualified lookup into dependent bases of class templates</a></li>
51 <li><a href="#undep_incomplete">Incomplete types in templates</a></li>
52 <li><a href="#bad_templates">Templates with no valid instantiations</a></li>
53 <li><a href="#default_init_const">Default initialization of const
54 variable of a class type requires user-defined default
58 <li><a href="#objective-c++">Objective-C++ compatibility</a>
60 <li><a href="#implicit-downcasts">Implicit downcasts</a></li>
63 <li><a href="#Use of class as method name">Use of class as method name</a></li>
68 <!-- ======================================================================= -->
69 <h2 id="c">C compatibility</h3>
70 <!-- ======================================================================= -->
72 <!-- ======================================================================= -->
73 <h3 id="inline">C99 inline functions</h3>
74 <!-- ======================================================================= -->
75 <p>By default, Clang builds C code according to the C99 standard,
76 which provides different inlining semantics than GCC's default
77 behavior. For example, when compiling the following code with no optimization:</p>
79 inline int add(int i, int j) { return i + j; }
87 <p>In C99, this is an incomplete (incorrect) program because there is
88 no external definition of the <code>add</code> function: the inline
89 definition is only used for optimization, if the compiler decides to
90 perform inlining. Therefore, we will get a (correct) link-time error
95 "_add", referenced from:
99 <p>There are several ways to fix this problem:</p>
102 <li>Change <code>add</code> to a <code>static inline</code>
103 function. Static inline functions are always resolved within the
104 translation unit, so you won't have to add an external, non-inline
105 definition of the function elsewhere in your program.</li>
107 <li>Provide an external (non-inline) definition of <code>add</code>
108 somewhere in your program.</li>
110 <li>Compile with the GNU89 dialect by adding
111 <code>-std=gnu89</code> to the set of Clang options. This option is
112 only recommended if the program source cannot be changed or if the
113 program also relies on additional C89-specific behavior that cannot
117 <!-- ======================================================================= -->
118 <h3 id="lvalue-cast">Lvalue casts</h3>
119 <!-- ======================================================================= -->
121 <p>Old versions of GCC permit casting the left-hand side of an assignment to a
122 different type. Clang produces an error on similar code, e.g.,</p>
125 lvalue.c:2:3: error: assignment to cast is illegal, lvalue casts are not
131 <p>To fix this problem, move the cast to the right-hand side. In this
132 example, one could use:</p>
138 <!-- ======================================================================= -->
139 <h3 id="blocks-in-protected-scope">Jumps to within <tt>__block</tt> variable scope</h3>
140 <!-- ======================================================================= -->
142 <p>Clang disallows jumps into the scope of a <tt>__block</tt> variable, similar
143 to the manner in which both GCC and Clang disallow jumps into the scope of
144 variables which have user defined constructors (in C++).</p>
146 <p>Variables marked with <tt>__block</tt> require special runtime initialization
147 before they can be used. A jump into the scope of a <tt>__block</tt> variable
148 would bypass this initialization and therefore the variable cannot safely be
151 <p>For example, consider the following code fragment:</p>
168 <p>GCC accepts this code, but it will crash at runtime along the error path,
169 because the runtime setup for the storage backing the <tt>x</tt> variable will
170 not have been initialized. Clang rejects this code with a hard error:</p>
173 t.c:3:5: error: goto into protected scope
176 t.c:5:15: note: jump bypasses setup of __block variable
181 <p>Some instances of this construct may be safe if the variable is never used
182 after the jump target, however the protected scope checker does not check the
183 uses of the variable, only the scopes in which it is visible. You should rewrite
184 your code to put the <tt>__block</tt> variables in a scope which is only visible
185 where they are used.</p>
187 <!-- ======================================================================= -->
188 <h2 id="objective-c">Objective-C compatibility</h3>
189 <!-- ======================================================================= -->
191 <!-- ======================================================================= -->
192 <h3 id="super-cast">Cast of super</h3>
193 <!-- ======================================================================= -->
195 <p>GCC treats the <code>super</code> identifier as an expression that
196 can, among other things, be cast to a different type. Clang treats
197 <code>super</code> as a context-sensitive keyword, and will reject a
198 type-cast of <code>super</code>:</p>
201 super.m:11:12: error: cannot cast 'super' (it isn't an expression)
202 [(Super*)super add:4];
206 <p>To fix this problem, remove the type cast, e.g.</p>
211 <!-- ======================================================================= -->
212 <h3 id="sizeof-interface">Size of interfaces</h3>
213 <!-- ======================================================================= -->
215 <p>When using the "non-fragile" Objective-C ABI in use, the size of an
216 Objective-C class may change over time as instance variables are added
217 (or removed). For this reason, Clang rejects the application of the
218 <code>sizeof</code> operator to an Objective-C class when using this
222 sizeof.m:4:14: error: invalid application of 'sizeof' to interface 'NSArray' in
224 int size = sizeof(NSArray);
228 <p>Code that relies on the size of an Objective-C class is likely to
229 be broken anyway, since that size is not actually constant. To address
230 this problem, use the Objective-C runtime API function
231 <code>class_getInstanceSize()</code>:</p>
234 class_getInstanceSize([NSArray class])
237 <!-- ======================================================================= -->
238 <h2 id="c++">C++ compatibility</h3>
239 <!-- ======================================================================= -->
241 <!-- ======================================================================= -->
242 <h3 id="vla">Variable-length arrays</h3>
243 <!-- ======================================================================= -->
245 <p>GCC and C99 allow an array's size to be determined at run
246 time. This extension is not permitted in standard C++. However, Clang
247 supports such variable length arrays in very limited circumstances for
248 compatibility with GNU C and C99 programs:</p>
251 <li>The element type of a variable length array must be a POD
252 ("plain old data") type, which means that it cannot have any
253 user-declared constructors or destructors, base classes, or any
254 members if non-POD type. All C types are POD types.</li>
256 <li>Variable length arrays cannot be used as the type of a non-type
257 template parameter.</li> </ul>
259 <p>If your code uses variable length arrays in a manner that Clang doesn't support, there are several ways to fix your code:
262 <li>replace the variable length array with a fixed-size array if you can
264 reasonable upper bound at compile time; sometimes this is as
265 simple as changing <tt>int size = ...;</tt> to <tt>const int size
266 = ...;</tt> (if the definition of <tt>size</tt> is a compile-time
267 integral constant);</li>
268 <li>use an <tt>std::string</tt> instead of a <tt>char []</tt>;</li>
269 <li>use <tt>std::vector</tt> or some other suitable container type;
271 <li>allocate the array on the heap instead using <tt>new Type[]</tt> -
272 just remember to <tt>delete[]</tt> it.</li>
275 <!-- ======================================================================= -->
276 <h3 id="init_static_const">Initialization of non-integral static const data members within a class definition</h3>
277 <!-- ======================================================================= -->
279 The following code is ill-formed in C++'03:
284 static const double SomeConstant = 0.5;
287 const double SomeClass::SomeConstant;
290 Clang errors with something similar to:
293 .../your_file.h:42:42: error: 'SomeConstant' can only be initialized if it is a static const integral data member
294 static const double SomeConstant = 0.5;
298 Only <i>integral</i> constant expressions are allowed as initializers
299 within the class definition. See C++'03 [class.static.data] p4 for the
300 details of this restriction. The fix here is straightforward: move
301 the initializer to the definition of the static data member, which
302 must exist outside of the class definition:
307 static const double SomeConstant;
310 const double SomeClass::SomeConstant<b> = 0.5</b>;
313 Note that the forthcoming C++0x standard will allow this.
315 <!-- ======================================================================= -->
316 <h3 id="dep_lookup">Unqualified lookup in templates</h3>
317 <!-- ======================================================================= -->
319 <p>Some versions of GCC accept the following invalid code:
322 template <typename T> T Squared(T x) {
323 return Multiply(x, x);
326 int Multiply(int x, int y) {
337 <pre> <b>my_file.cpp:2:10: <span class="error">error:</span> use of undeclared identifier 'Multiply'</b>
338 return Multiply(x, x);
339 <span class="caret"> ^</span>
341 <b>my_file.cpp:10:3: <span class="note">note:</span> in instantiation of function template specialization 'Squared<int>' requested here</b>
343 <span class="caret"> ^</span>
346 <p>The C++ standard says that unqualified names like <q>Multiply</q>
347 are looked up in two ways.
349 <p>First, the compiler does <i>unqualified lookup</i> in the scope
350 where the name was written. For a template, this means the lookup is
351 done at the point where the template is defined, not where it's
352 instantiated. Since <tt>Multiply</tt> hasn't been declared yet at
353 this point, unqualified lookup won't find it.
355 <p>Second, if the name is called like a function, then the compiler
356 also does <i>argument-dependent lookup</i> (ADL). (Sometimes
357 unqualified lookup can suppress ADL; see [basic.lookup.argdep]p3 for
358 more information.) In ADL, the compiler looks at the types of all the
359 arguments to the call. When it finds a class type, it looks up the
360 name in that class's namespace; the result is all the declarations it
361 finds in those namespaces, plus the declarations from unqualified
362 lookup. However, the compiler doesn't do ADL until it knows all the
365 <p>In our example, <tt>Multiply</tt> is called with dependent
366 arguments, so ADL isn't done until the template is instantiated. At
367 that point, the arguments both have type <tt>int</tt>, which doesn't
368 contain any class types, and so ADL doesn't look in any namespaces.
369 Since neither form of lookup found the declaration
370 of <tt>Multiply</tt>, the code doesn't compile.
372 <p>Here's another example, this time using overloaded operators,
373 which obey very similar rules.
375 <pre>#include <iostream>
377 template<typename T>
378 void Dump(const T& value) {
379 std::cout << value << "\n";
386 std::ostream& operator<<(std::ostream& out, ns::Data data) {
387 return out << "Some data";
394 <p>Again, Clang complains about not finding a matching function:</p>
397 <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>
398 std::cout << value << "\n";
399 <span class="caret">~~~~~~~~~ ^ ~~~~~</span>
400 <b>my_file.cpp:17:3: <span class="note">note:</span> in instantiation of function template specialization 'Dump<ns::Data>' requested here</b>
402 <span class="caret">^</span>
405 <p>Just like before, unqualified lookup didn't find any declarations
406 with the name <tt>operator<<</tt>. Unlike before, the argument
407 types both contain class types: one of them is an instance of the
408 class template type <tt>std::basic_ostream</tt>, and the other is the
409 type <tt>ns::Data</tt> that we declared above. Therefore, ADL will
410 look in the namespaces <tt>std</tt> and <tt>ns</tt> for
411 an <tt>operator<<</tt>. Since one of the argument types was
412 still dependent during the template definition, ADL isn't done until
413 the template is instantiated during <tt>Use</tt>, which means that
414 the <tt>operator<<</tt> we want it to find has already been
415 declared. Unfortunately, it was declared in the global namespace, not
416 in either of the namespaces that ADL will look in!
418 <p>There are two ways to fix this problem:</p>
419 <ol><li>Make sure the function you want to call is declared before the
420 template that might call it. This is the only option if none of its
421 argument types contain classes. You can do this either by moving the
422 template definition, or by moving the function definition, or by
423 adding a forward declaration of the function before the template.</li>
424 <li>Move the function into the same namespace as one of its arguments
425 so that ADL applies.</li></ol>
427 <p>For more information about argument-dependent lookup, see
428 [basic.lookup.argdep]. For more information about the ordering of
429 lookup in templates, see [temp.dep.candidate].
431 <!-- ======================================================================= -->
432 <h3 id="dep_lookup_bases">Unqualified lookup into dependent bases of class templates</h3>
433 <!-- ======================================================================= -->
435 Some versions of GCC accept the following invalid code:
438 template <typename T> struct Base {
440 static void DoThat(T x) {}
443 template <typename T> struct Derived : public Base<T> {
445 DoThis(x); // Invalid!
446 DoThat(x); // Invalid!
451 Clang correctly rejects it with the following errors
452 (when <tt>Derived</tt> is eventually instantiated):
455 my_file.cpp:8:5: error: use of undeclared identifier 'DoThis'
459 my_file.cpp:2:8: note: must qualify identifier to find this declaration in dependent base class
462 my_file.cpp:9:5: error: use of undeclared identifier 'DoThat'
466 my_file.cpp:3:15: note: must qualify identifier to find this declaration in dependent base class
467 static void DoThat(T x) {}
470 Like we said <a href="#dep_lookup">above</a>, unqualified names like
471 <tt>DoThis</tt> and <tt>DoThat</tt> are looked up when the template
472 <tt>Derived</tt> is defined, not when it's instantiated. When we look
473 up a name used in a class, we usually look into the base classes.
474 However, we can't look into the base class <tt>Base<T></tt>
475 because its type depends on the template argument <tt>T</tt>, so the
476 standard says we should just ignore it. See [temp.dep]p3 for details.
478 <p>The fix, as Clang tells you, is to tell the compiler that we want a
479 class member by prefixing the calls with <tt>this-></tt>:
483 <b>this-></b>DoThis(x);
484 <b>this-></b>DoThat(x);
488 Alternatively, you can tell the compiler exactly where to look:
492 <b>Base<T></b>::DoThis(x);
493 <b>Base<T></b>::DoThat(x);
497 This works whether the methods are static or not, but be careful:
498 if <tt>DoThis</tt> is virtual, calling it this way will bypass virtual
501 <!-- ======================================================================= -->
502 <h3 id="undep_incomplete">Incomplete types in templates</h3>
503 <!-- ======================================================================= -->
505 The following code is invalid, but compilers are allowed to accept it:
509 template <class T> bool read(T &value) {
511 return read(opts, value);
514 class IOOptions { bool ForceReads; };
515 bool read(const IOOptions &opts, int &x);
516 template bool read<>(int &);
519 The standard says that types which don't depend on template parameters
520 must be complete when a template is defined if they affect the
521 program's behavior. However, the standard also says that compilers
522 are free to not enforce this rule. Most compilers enforce it to some
523 extent; for example, it would be an error in GCC to
524 write <tt>opts.ForceReads</tt> in the code above. In Clang, we feel
525 that enforcing the rule consistently lets us provide a better
526 experience, but unfortunately it also means we reject some code that
527 other compilers accept.
529 <p>We've explained the rule here in very imprecise terms; see
530 [temp.res]p8 for details.
532 <!-- ======================================================================= -->
533 <h3 id="bad_templates">Templates with no valid instantiations</h3>
534 <!-- ======================================================================= -->
536 The following code contains a typo: the programmer
537 meant <tt>init()</tt> but wrote <tt>innit()</tt> instead.
540 template <class T> class Processor {
546 template <class T> void process() {
547 Processor<T> processor;
548 processor.innit(); // <-- should be 'init()'
553 Unfortunately, we can't flag this mistake as soon as we see it: inside
554 a template, we're not allowed to make assumptions about "dependent
555 types" like <tt>Processor<T></tt>. Suppose that later on in
556 this file the programmer adds an explicit specialization
557 of <tt>Processor</tt>, like so:
560 template <> class Processor<char*> {
565 Now the program will work — as long as the programmer only ever
566 instantiates <tt>process()</tt> with <tt>T = char*</tt>! This is why
567 it's hard, and sometimes impossible, to diagnose mistakes in a
568 template definition before it's instantiated.
570 <p>The standard says that a template with no valid instantiations is
571 ill-formed. Clang tries to do as much checking as possible at
572 definition-time instead of instantiation-time: not only does this
573 produce clearer diagnostics, but it also substantially improves
574 compile times when using pre-compiled headers. The downside to this
575 philosophy is that Clang sometimes fails to process files because they
576 contain broken templates that are no longer used. The solution is
577 simple: since the code is unused, just remove it.
579 <!-- ======================================================================= -->
580 <h3 id="default_init_const">Default initialization of const variable of a class type requires user-defined default constructor</h3>
581 <!-- ======================================================================= -->
583 If a <tt>class</tt> or <tt>struct</tt> has no user-defined default
584 constructor, C++ doesn't allow you to default construct a <tt>const</tt>
585 instance of it like this ([dcl.init], p9):
590 // The compiler-supplied default constructor works fine, so we
591 // don't bother with defining one.
596 const Foo foo; // Error!
601 To fix this, you can define a default constructor for the class:
611 const Foo foo; // Now the compiler is happy.
616 <!-- ======================================================================= -->
617 <h2 id="objective-c++">Objective-C++ compatibility</h3>
618 <!-- ======================================================================= -->
620 <!-- ======================================================================= -->
621 <h3 id="implicit-downcasts">Implicit downcasts</h3>
622 <!-- ======================================================================= -->
624 <p>Due to a bug in its implementation, GCC allows implicit downcasts
625 (from base class to a derived class) when calling functions. Such code is
626 inherently unsafe, since the object might not actually be an instance
627 of the derived class, and is rejected by Clang. For example, given
632 @interface Derived : Base @end
640 <p>Clang produces the following error:</p>
643 downcast.mm:6:3: error: no matching function for call to 'f'
646 downcast.mm:4:6: note: candidate function not viable: cannot convert from
647 superclass 'Base *' to subclass 'Derived *' for 1st argument
652 <p>If the downcast is actually correct (e.g., because the code has
653 already checked that the object has the appropriate type), add an
660 <!-- ======================================================================= -->
661 <h3 id="Use of class as method name">Use of class as method name</h3>
662 <!-- ======================================================================= -->
664 <p>Use of 'class' name to declare a method is allowed in objective-c++ mode to
665 be compatible with GCC. However, use of property dot syntax notation to call
666 this method is not allowed in clang++, as [I class] is a suitable syntax that
667 will work. So, this test will fail in clang++.
677 - (int) Meth { return I.class; }