
In order to better understand Clang, a compiler front-end for C, C++, Objective-C++, and Objective-C, you have to start with the LLVM project. LLVM is short for Low-Level Virtual Machine; it’s an intermediate compiler language (i.e., LLVM IR) similar in concept to bytecode or .il. Clang compiles the C/C++/Objective-C source code and outputs LLVM IR instructions, which are low-level RISC-like. The LLVM backend then generates the appropriate machine code for the targeted processor and system (which could include any X86, X86-64, PowerPC, PowerPC-64, ARM, Thumb, SPARC, Alpha, CellSPU, MIPS, MSP430, SystemZ, or XCore system). Although the LLVM infrastructure is open-source, the U.S. National Science Foundation, Apple, the University of Illinois, AutoESL Design Technologies, and others have all sponsored its development. Apple in particular has funded a lot of development since 2005, with Clang replacing GCC for iOS and Mac OS development in 2011. The idea with Clang and LLVM is that you can mix the compiler front-end with a targeted back-end and end up with highly portable and efficient compiler. Front-end compilers exist for C, C++, Common Lisp, ActionScript, Ada, D, Fortran, OpenGL Shading Language, Go, Haskell, Java bytecode, Julia, Objective-C, Swift, Python, R, Ruby, Rust, Scala, C# and Lua. Clang itself was open-sourced in 2007.
What Makes Clang Better?
It can perform static analysis of your code, whether in C, C++ or Objective-C. This functionality is built into the Xcode version that runs on the Mac, with instructions provided to build the static analyzer on other platforms. Static analysis is a technique whereby the program is read and ‘understood’ to the point where obvious bugs are automatically detected, such as dead code, memory leaks, double-frees, bad pointer references, and other such conditions.Write Clang Tools
Clang lets you write tools that give you information about a program. There are three ways to do this:- Use LibCLang, a high-level C interface to Clang. This should be your first port of call, as it lets you access Clang from languages other than C++, as well as walk through the AST using a cursor. (AST is short for Abstract syntax tree, and is the output of the front end before generating the LLVM IR code that is used by the backend. Here’s a useful introduction to the Clang AST.)
- You can write plugins for Clang to modify the compile process.
- The third way is to use LibTooling, a C++ interface that lets you write standalone tools.