Sunday, January 22, 2012

Creating Executable files in C

Unlike any other languages C is the most efficient language which has rich set of operators and due to its non-restrictions and generality makes it convenient for programming in many areas. In this post, i would like to show, how to create your own executable commands, like general shell commands i.e,
cp - copy command for copying files,      ls - for listing all enteries within a directory,     mv - command for moving files    etc. This task is very simple.
Firstly create a C file using any editor with 'c' as extension at the end. For example, here i am using a vim editor and create a C file which prints anything you give.
vim printprogram.c

now i am going to  write the following code in the created file
// program to print input 

#include     // library file
#define FILE_END EOF     //symbolic constants

main()     // start point 
   char k ;    // variable declarations
   printf("Enter & press Ctrl+D when finished:");
   //getchar for input 
   while ( (k = getchar()) != FILE_END )  {
      putchar(k);    //output
}              // end point    
after coding the file, thus proceed for its working ie, compile the file by typing the following command in the terminal
cc printprogram.c -o printpg

'cc' is the complier or you can use 'gcc' since both are same. The option '-o ' is to copy the generated machine-executable code to a file print. Now check whether it runs by again typing in the terminal, the following command

Here the ' . ' means current directory and ' ./ ' means inside the current directory to execute the file ' printpg '. If the file is running correctly then you can proceed to next step.
change the permission of the file
chmod -c 777 printpg
Now copy the file to the bin directory, where the executable files can be run without using ' ./ ' in the terminal.
sudo cp printpg /bin/
Remove the file print in your current directory
rm printpg
now just type print in the terminal
Atlast your executable file is ready to use.

No comments:

Post a Comment