Sunday, 28 August 2011

Howto Compiling C program and creating executable file under Linux / UNIX / *BSD

How do I compile C program and create an executable file under Linux or UNIX operating systems?

You need GNU project C and C++ compiler for compiling C program and creating an executable file. Most Unix and Linux (*BSD) user start compiling their C program by the name cc. But you can use gcc command to compile program. First make sure you have gcc installed:

Make Sure Compiler Is Installed

Type the following command to verify that gcc is installed:
which gcc
Output:
/usr/bin/gcc
Find out version of gcc:
$ gcc --version
Output:
gcc (GCC) 4.0.3 20060212 (prerelease) (Debian 4.0.2-9)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
To compile C program you need to use syntax as follows:
gcc program.c -o program-output

Writing Your First C Program Under Linux / UNIX

Use a text editor such as vi or gedit to create a C program called first.c:
$ vi first.c
Type the following lines (program):
#include <stdio.h>
int main(void){
printf("My first C program\n");
return 0;
}

How Do I Compile My Program?

To compile C program first.c, and create an executable file called first, enter:
$ gcc first.c -o first
OR
$ cc first.c -o first
To execute program first, enter:
$ ./first
Output:
My first C program
However, both FreeBSD and Linux support direct make (GNU make utility to maintain groups of programs) command on C program without writing a make file. Remove, first program using the rm command:
$ rm first
$ make first

Output:
cc   first.o   -o first
Execute program first:
$ ./first
Please note that above hack works with GNU make only.

No comments:

Post a Comment