# Language Compatibility

Clang strives to both conform to current language standards (C99, C++98) and also to implement many widely-used extensions available in other compilers, so that most correct code will "just work" when compiler with Clang. However, Clang is more strict than other popular compilers, and may reject incorrect code that other compilers allow. This page documents common compatibility and portability issues with Clang to help you understand and fix the problem in your code when Clang emits an error message.

- C compatibility
  - C99 inline functions
  - "missing" vector __builtin functions
  - Lvalue casts
  - Jumps to within `__block` variable scope
- Objective-C compatibility
  - Cast of super
  - Size of interfaces
  - Internal Objective-C types
- C++ compatibility
  - Variable-length arrays
  - Unqualified lookup in templates
  - Unqualified lookup into dependent bases of class templates
  - Incomplete types in templates
  - Templates with no valid instantiations
  - Default initialization of const variable of a class type requires user-defined default constructor
- Objective-C++ compatibility
  - Implicit downcasts
  - Use of class as method name

## C compatibility

### C99 inline functions

By default, Clang builds C code according to the C99 standard, which provides different inlining semantics than GCC's default behavior. For example, when compiling the following code with no optimization:

    inline int add(int i, int j) { return i + j; }

    int main() {
      int i = add(4, 5);
      return i;
    }

In C99, this is an incomplete (incorrect) program because there is no external definition of the `add` function: the inline definition is only used for optimization, if the compiler decides to perform inlining. Therefore, we will get a (correct) link-time error with Clang, e.g.:

    Undefined symbols:
      "_add", referenced from:
          _main in cc-y1jXIr.o

There are several ways to fix this problem:

- Change `add` to a `static inline` function. Static inline functions are always resolved within the translation unit, so you won't have to add an external, non-inline definition of the function elsewhere in your program.
- Provide an external (non-inline) definition of `add` somewhere in your program.
- Compile with the GNU89 dialect by adding `-std=gnu89` to the set of Clang options. This option is only recommended if the program source cannot be changed or if the program also relies on additional C89-specific behavior that cannot be changed.

### "missing" vector __builtin functions

The Intel and AMD manuals document a number "`<*mmintrin.h>`" header files, which define a standardized API for accessing vector operations on X86 CPUs. These functions have names like `_mm_xor_ps` and `_mm256_addsub_pd`. Compilers have leeway to implement these functions however they want. Since Clang supports an excellent set of native vector operations, the Clang headers implement these interfaces in terms of the native vector operations.

In contrast, GCC implements these functions mostly as a 1-to-1 mapping to builtin function calls, like `__builtin_ia32_paddw128`. These builtin functions are an internal implementation detail of GCC, and are not portable to the Intel compiler, the Microsoft compiler, or Clang. If you get build errors mentioning these, the fix is simple: switch to the *mmintrin.h functions.

The same issue occurs for NEON and Altivec for the ARM and PowerPC architectures respectively. For these, make sure to use the <arm_neon.h> and <altivec.h> headers.

### Lvalue casts

Old versions of GCC permit casting the left-hand side of an assignment to a different type. Clang produces an error on similar code, e.g.,

    lvalue.c:2:3: error: assignment to cast is illegal, lvalue casts are not
          supported
      (int*)addr = val;
      ^~~~~~~~~~ ~

To fix this problem, move the cast to the right-hand side. In this example, one could use:

      addr = (float *)val;

### Jumps to within `__block` variable scope

Clang disallows jumps into the scope of a `__block` variable, similar to the manner in which both GCC and Clang disallow jumps into the scope of variables which have user defined constructors (in C++).

Variables marked with `__block` require special runtime initialization before they can be used. A jump into the scope of a `__block` variable would bypass this initialization and therefore the variable cannot safely be used.

For example, consider the following code fragment:

    int f0(int c) {
      if (c)
        goto error;

      __block int x;
      x = 1;
      return x;

     error:
      x = 0;
      return x;
    }

GCC accepts this code, but it will crash at runtime along the error path, because the runtime setup for the storage backing the `x` variable will not have been initialized. Clang rejects this code with a hard error:

    t.c:3:5: error: goto into protected scope
        goto error;
        ^
    t.c:5:15: note: jump bypasses setup of __block variable
      __block int x;
                  ^

Some instances of this construct may be safe if the variable is never used after the jump target, however the protected scope checker does not check the uses of the variable, only the scopes in which it is visible. You should rewrite your code to put the `__block` variables in a scope which is only visible where they are used.

## Objective-C compatibility

### Cast of super

GCC treats the `super` identifier as an expression that can, among other things, be cast to a different type. Clang treats `super` as a context-sensitive keyword, and will reject a type-cast of `super`:

    super.m:11:12: error: cannot cast 'super' (it isn't an expression)
      [(Super*)super add:4];
       ~~~~~~~~^

To fix this problem, remove the type cast, e.g.

      [super add:4];

### Size of interfaces

When using the "non-fragile" Objective-C ABI in use, the size of an Objective-C class may change over time as instance variables are added (or removed). For this reason, Clang rejects the application of the `sizeof` operator to an Objective-C class when using this ABI:

    sizeof.m:4:14: error: invalid application of 'sizeof' to interface 'NSArray' in
          non-fragile ABI
      int size = sizeof(NSArray);
                 ^     ~~~~~~~~~

Code that relies on the size of an Objective-C class is likely to be broken anyway, since that size is not actually constant. To address this problem, use the Objective-C runtime API function `class_getInstanceSize()`:

      class_getInstanceSize([NSArray class])

### Internal Objective-C types

GCC allows using pointers to internal Objective-C objects, `struct objc_object*`, `struct objc_selector*`, and `struct objc_class*` in place of the types `id`, `SEL`, and `Class` respectively. Clang treats the internal Objective-C structures as implementation detail and won't do implicit conversions:

    t.mm:11:2: error: no matching function for call to 'f'
            f((struct objc_object *)p);
            ^
    t.mm:5:6: note: candidate function not viable: no known conversion from 'struct objc_object *' to 'id' for 1st argument
    void f(id x);
         ^

Code should use types `id`, `SEL`, and `Class` instead of the internal types.

## C++ compatibility

### Variable-length arrays

GCC and C99 allow an array's size to be determined at run time. This extension is not permitted in standard C++. However, Clang supports such variable length arrays in very limited circumstances for compatibility with GNU C and C99 programs:

- The element type of a variable length array must be a POD ("plain old data") type, which means that it cannot have any user-declared constructors or destructors, base classes, or any members if non-POD type. All C types are POD types.
- Variable length arrays cannot be used as the type of a non-type template parameter.

If your code uses variable length arrays in a manner that Clang doesn't support, there are several ways to fix your code:

1. replace the variable length array with a fixed-size array if you can determine a reasonable upper bound at compile time; sometimes this is as simple as changing `int size = ...;` to `const int size = ...;` (if the definition of `size` is a compile-time integral constant);
2. use an `std::string` instead of a `char []`;
3. use `std::vector` or some other suitable container type; or
4. allocate the array on the heap instead using `new Type[]` - just remember to `delete[]` it.

### Unqualified lookup in templates

Some versions of GCC accept the following invalid code:

    template <typename T> T Squared(T x) {
      return Multiply(x, x);
    }

    int Multiply(int x, int y) {
      return x * y;
    }

    int main() {
      Squared(5);
    }

Clang complains:

      my_file.cpp:2:10: error: use of undeclared identifier 'Multiply'
        return Multiply(x, x);
               ^

      my_file.cpp:10:3: note: in instantiation of function template specialization 'Squared<int>' requested here
        Squared(5);
        ^

The C++ standard says that unqualified names like Multiply are looked up in two ways.

First, the compiler does unqualified lookup in the scope where the name was written. For a template, this means the lookup is done at the point where the template is defined, not where it's instantiated. Since `Multiply` hasn't been declared yet at this point, unqualified lookup won't find it.

Second, if the name is called like a function, then the compiler also does argument-dependent lookup (ADL). (Sometimes unqualified lookup can suppress ADL; see [basic.lookup.argdep]p3 for more information.) In ADL, the compiler looks at the types of all the arguments to the call. When it finds a class type, it looks up the name in that class's namespace; the result is all the declarations it finds in those namespaces, plus the declarations from unqualified lookup. However, the compiler doesn't do ADL until it knows all the argument types.

In our example, `Multiply` is called with dependent arguments, so ADL isn't done until the template is instantiated. At that point, the arguments both have type `int`, which doesn't contain any class types, and so ADL doesn't look in any namespaces. Since neither form of lookup found the declaration of `Multiply`, the code doesn't compile.

Here's another example, this time using overloaded operators, which obey very similar rules.

    #include <iostream>

    template<typename T>
    void Dump(const T& value) {
      std::cout << value << "\n";
    }

    namespace ns {
      struct Data {};
    }

    std::ostream& operator<<(std::ostream& out, ns::Data data) {
      return out << "Some data";
    }

    void Use() {
      Dump(ns::Data());
    }

Again, Clang complains about not finding a matching function:

    my_file.cpp:5:13: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ns::Data const')
      std::cout << value << "\n";
      ~~~~~~~~~ ^  ~~~~~
    my_file.cpp:17:3: note: in instantiation of function template specialization 'Dump<ns::Data>' requested here
      Dump(ns::Data());
      ^

Just like before, unqualified lookup didn't find any declarations with the name `operator<<`. Unlike before, the argument types both contain class types: one of them is an instance of the class template type `std::basic_ostream`, and the other is the type `ns::Data` that we declared above. Therefore, ADL will look in the namespaces `std` and `ns` for an `operator<<`. Since one of the argument types was still dependent during the template definition, ADL isn't done until the template is instantiated during `Use`, which means that the `operator<<` we want it to find has already been declared. Unfortunately, it was declared in the global namespace, not in either of the namespaces that ADL will look in!

There are two ways to fix this problem:

1. Make sure the function you want to call is declared before the template that might call it. This is the only option if none of its argument types contain classes. You can do this either by moving the template definition, or by moving the function definition, or by adding a forward declaration of the function before the template.
2. Move the function into the same namespace as one of its arguments so that ADL applies.

For more information about argument-dependent lookup, see [basic.lookup.argdep]. For more information about the ordering of lookup in templates, see [temp.dep.candidate].

### Unqualified lookup into dependent bases of class templates

Some versions of GCC accept the following invalid code:

    template <typename T> struct Base {
      void DoThis(T x) {}
      static void DoThat(T x) {}
    };

    template <typename T> struct Derived : public Base<T> {
      void Work(T x) {
        DoThis(x);  // Invalid!
        DoThat(x);  // Invalid!
      }
    };

Clang correctly rejects it with the following errors (when `Derived` is eventually instantiated):

    my_file.cpp:8:5: error: use of undeclared identifier 'DoThis'
        DoThis(x);
        ^
        this->
    my_file.cpp:2:8: note: must qualify identifier to find this declaration in dependent base class
      void DoThis(T x) {}
           ^
    my_file.cpp:9:5: error: use of undeclared identifier 'DoThat'
        DoThat(x);
        ^
        this->
    my_file.cpp:3:15: note: must qualify identifier to find this declaration in dependent base class
      static void DoThat(T x) {}

Like we said above, unqualified names like `DoThis` and `DoThat` are looked up when the template `Derived` is defined, not when it's instantiated. When we look up a name used in a class, we usually look into the base classes. However, we can't look into the base class `Base<T>` because its type depends on the template argument `T`, so the standard says we should just ignore it. See [temp.dep]p3 for details.

The fix, as Clang tells you, is to tell the compiler that we want a class member by prefixing the calls with `this->`:

      void Work(T x) {
        this->DoThis(x);
        this->DoThat(x);
      }

Alternatively, you can tell the compiler exactly where to look:

      void Work(T x) {
        Base<T>::DoThis(x);
        Base<T>::DoThat(x);
      }

This works whether the methods are static or not, but be careful: if `DoThis` is virtual, calling it this way will bypass virtual dispatch!

### Incomplete types in templates

The following code is invalid, but compilers are allowed to accept it:

      class IOOptions;
      template <class T> bool read(T &value) {
        IOOptions opts;
        return read(opts, value);
      }

      class IOOptions { bool ForceReads; };
      bool read(const IOOptions &opts, int &x);
      template bool read<>(int &);

The standard says that types which don't depend on template parameters must be complete when a template is defined if they affect the program's behavior. However, the standard also says that compilers are free to not enforce this rule. Most compilers enforce it to some extent; for example, it would be an error in GCC to write `opts.ForceReads` in the code above. In Clang, we feel that enforcing the rule consistently lets us provide a better experience, but unfortunately it also means we reject some code that other compilers accept.

We've explained the rule here in very imprecise terms; see [temp.res]p8 for details.

### Templates with no valid instantiations

The following code contains a typo: the programmer meant `init()` but wrote `innit()` instead.

      template <class T> class Processor {
        ...
        void init();
        ...
      };
      ...
      template <class T> void process() {
        Processor<T> processor;
        processor.innit();       // <-- should be 'init()'
        ...
      }

Unfortunately, we can't flag this mistake as soon as we see it: inside a template, we're not allowed to make assumptions about "dependent types" like `Processor<T>`. Suppose that later on in this file the programmer adds an explicit specialization of `Processor`, like so:

      template <> class Processor<char*> {
        void innit();
      };

Now the program will work — as long as the programmer only ever instantiates `process()` with `T = char*`! This is why it's hard, and sometimes impossible, to diagnose mistakes in a template definition before it's instantiated.

The standard says that a template with no valid instantiations is ill-formed. Clang tries to do as much checking as possible at definition-time instead of instantiation-time: not only does this produce clearer diagnostics, but it also substantially improves compile times when using pre-compiled headers. The downside to this philosophy is that Clang sometimes fails to process files because they contain broken templates that are no longer used. The solution is simple: since the code is unused, just remove it.

### Default initialization of const variable of a class type requires user-defined default constructor

If a `class` or `struct` has no user-defined default constructor, C++ doesn't allow you to default construct a `const` instance of it like this ([dcl.init], p9):

    class Foo {
     public:
      // The compiler-supplied default constructor works fine, so we
      // don't bother with defining one.
      ...
    };

    void Bar() {
      const Foo foo;  // Error!
      ...
    }

To fix this, you can define a default constructor for the class:

    class Foo {
     public:
      Foo() {}
      ...
    };

    void Bar() {
      const Foo foo;  // Now the compiler is happy.
      ...
    }

## Objective-C++ compatibility

### Implicit downcasts

Due to a bug in its implementation, GCC allows implicit downcasts (from base class to a derived class) when calling functions. Such code is inherently unsafe, since the object might not actually be an instance of the derived class, and is rejected by Clang. For example, given this code:

    @interface Base @end
    @interface Derived : Base @end

    void f(Derived *);
    void g(Base *base) {
      f(base);
    }

Clang produces the following error:

    downcast.mm:6:3: error: no matching function for call to 'f'
      f(base);
      ^
    downcast.mm:4:6: note: candidate function not viable: cannot convert from
          superclass 'Base *' to subclass 'Derived *' for 1st argument
    void f(Derived *);
         ^

If the downcast is actually correct (e.g., because the code has already checked that the object has the appropriate type), add an explicit cast:

      f((Derived *)base);

### Use of class as method name

Use of 'class' name to declare a method is allowed in objective-c++ mode to be compatible with GCC. However, use of property dot syntax notation to call this method is not allowed in clang++, as [I class] is a suitable syntax that will work. So, this test will fail in clang++.

    @interface I {
    int cls;
    }
    + (int)class;
    @end

    @implementation  I
    - (int) Meth { return I.class; }
    @end