What is Clang ? How to compile C program using clang ?

What is Clang ?

Clang is a compiler front end for the C, C++, Objective-C and Objective-C++ programming languages. It uses the LLVM compiler infrastructure as its back end. It is designed to act as a drop-in replacement for the GNU Compiler Collection (GCC), supporting most of its compilation flags and unofficial language extensions. Clang is opensource software . The Clang project includes the Clang front end, a static analyzer, and several code analysis tools. [ Source: Wikipedia ]

Compiling C program using clang on Ubuntu.

Now, as we have seen above clang is developed as an alternative to GCC GNU C Compiler hence lets see how we can compile and execute simple C program using clang.

 $ sudo apt install clang 

The following NEW packages will be installed: binfmt-support clang clang-6.0 libclang-common-6.0-dev libclang1-6.0 libffi-dev libobjc-7-dev libobjc4 libomp-dev libomp5 libtinfo-dev llvm-6.0 llvm-6.0-dev llvm-6.0-runtime

As we can see above installing clang on ubuntu also installs LLVM. Now, lets write our simple C program as,

 $ vim helloworld.c 
#include <stdio.h>

int main(int argc, char **argv) {
        printf("Hello World\n");
        return 0;
}

Now, we can compile the program using clang as below,

 $ clang helloworld.c 

Above command generates binary executable with default name a.out, now we can execute the program as below,

 $ ./a.out 
Hello World

If we want to give different name to executable, we can do the same in a similar way as we do with gcc

 $ clang -o hello helloworld.c 
 $ ./hello 
Hello World 
 $ ls -l hello
-rwxr-xr-x 1 devlab devlab 8184 Jul  5 08:21 hello

If we want to generate optimised binary executable pass “-Oz” as additional parameter to above command to generate binary with maximum possible optimisation

 $ clang -o hello helloworld.c -Oz 

References – http://clang.llvm.org/get_started.html

Follow Lynxbee

Leave a Reply / Ask Question