Tuesday, March 6, 2012

Some useful commands in C programming

Recently I have used C for one of my projects. Here are some commands which make it easy for me to compile simple C source files.

Once you save the C source code in source_file_name.c file, you can compile it with gcc command.

gcc source_file_name.c 

This command will compile your source code. The output file name will be a.out. But if you need to give the output file a name you prefer, you can simply give the following command.

gcc source_file_name.c -o output_file_name

Then it will write the object code (compiled code) in to the file "output_file_name".

You can then run the file by just giving its name in the terminal.

$ ./output_file_name

But these are two separate commands. If you need to compile and run your C program using just one command, then you can use the following command.

gcc source_file_name.c -o output_file_name && ./output_file_name

This will compile your source code first and if compilation is successful it will execute the program.

Very basic stuff, but useful. Isn't it :)

note : Why we need to use ./ to execute a program ? 

It is because, in Linux operating systems, to run a program we need to specify the directory where that program file is located. Here ./ means "Current Directory". Otherwise the directory should be listed in the PATH system variable.