Clang is a new C/C++/Objective-C/Objectice-C++ compiler being developed on top of LLVM. Clang is open-source, and its development is being sponsored by Apple. I'm writing this post to try to convince you that you should switch to using it by default for your local development if you're targetting Mac or Linux at least. Clang tries to act as a drop-in replacement for gcc, by trying to immitate its command line argument syntax and semantics, which means that in most cases you can switch from gcc to clang by just changing the name of the compiler you're using. This means that switching to clang is going to be really easy, but it also provides at least two useful features which make it really better than gcc for local development:
- Compilation speed. Clang is usually a lot faster to compile than gcc is. It's been quite a while since I did measurements, but I've seen compile times up to twice as fast with clang compared to gcc. Yes. You read right. That's twice!.
- Better compiler diagnostics. Clang usually provides much better diagnostics in case your code fails to compile, which means that you need to spend less time trying to understand what you should do to fix your code. It even goes further by suggesting you of the most likely fixes. I'll give you two examples!
Consider the following program:``` void foobar();
int main() { foobaz(); }
test.cpp:4:3: error: use of undeclared identifier 'foobaz'; did you mean 'foobar'? foobaz(); ^~~~~~ foobar test.cpp:1:6: note: 'foobar' declared here void foobar(); ^ 1 error generated.
Here's another program, followed by clang's output:```
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
struct X {}
int main() {
int x = MIN(2,X());
}
test.cpp:2:12: error: expected ‘;’ after struct struct X {} ^ ; test.cpp:5:11: error: invalid operands to binary expression (‘int’ and ‘X’) int x = MIN(2,X()); ^~~~~~~~~~ test.cpp:1:24: note: instantiated from: #define MIN(a,b) (((a) < (b)) ? (a) : (b)) ~~~ ^ ~~~ 2 errors generated.
Now if that has not made you drool yet, you can check out this page for more reasons why clang provides better diagnostics than gcc does. For the impatient, here is how you would build and install clang locally on Mac and Linux. You can check out this page for more comprehensive documentation. Note that the clang port is not ready for everyday use yet, so I won't recommend you switching to clang if you're on Windows.mkdir /path/to/clang-build cd /path/to/clang-build svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm cd llvm/tools svn co http://llvm.org/svn/llvm-project/cfe/trunk clang cd ../.. mkdir build cd build ../llvm/configure --enable-optimized --disable-assertions make && sudo make install
At this point, clang should be installed to /usr/local. In order to use it, you should add the following two lines to your mozconfig file:```
export CC=clang
export CXX=clang++