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,

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )


$ 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


Leave a Comment

Android Android Build system Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded