Skip to main content

Programming in C using gcc in Linux

If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line −

$ gcc -v


If you have GNU compiler installed on your machine, then it should print a message.If GCC is not installed, then you will have to install it yourself using the detailed instructions available at


Install GCC

The following linux command will install gcc compiler on Ubuntu 18.04 Bionic Beaver( Latest version is 20.04 Focal Fossa) .Open up terminal and enter: 
$sudo apt-get install gcc

Install build-essential
Another way to install gcc compiler is to install it as part of build-essential package. build-essential package will also install additional libraries as well as g++ compiler. In most cases or if unsure this is exactly what you need:
$sudo apt-get install build-essential

Check GCC version
Confirm your installation by checking for GCC version:
$ gcc --version

Writing first program:
Following is first program in C

/* my first program */
#include <stdio.h>
int main(void)
{
printf("Hello World");
return 0;
}
Output:Hello World

Let us analyze the program line by line.
Line 0: [ /*my first program / ] In a C program, multi line comments are included between / * */. Comments are ingored by the compiler.Comments improve the readability and helps in documentation.It is a good practise to add commands at various sections of the program.Single line commands can also be added with //.

Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by preprocessor which is a program invoked by the compiler. In a very basic term, preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the above example, preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C. These header files generally contain declaration of functions. We need stdio.h for the function printf() used in the program.

Line 2 [ int main(void) ] There must to be starting point from where execution of compiled C program begins. In C, the execution typically begins with first line of main(). The void written in brackets indicates that the main doesn’t take any parameter . main() can be written to take parameters also. We will be covering that in future posts.
The int written before main indicates return type of main(). The value returned by main indicates status of program termination.

Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define a scope and mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets.
Line 4 [ printf(“Hello world”); ] printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, semicolon is always used to indicate end of statement.

3)Compile and Execute C Program
Let us see how to save the source code in a file, and how to compile and run it. Following are the simple steps −
  • Open a text editor and add the above-mentioned code.(vi,emac,gedit)
  • Save the file as hello.c
  • Open a command prompt and go to the directory where you have saved the file.
  • Type gcc hello.c and press enter to compile your code.
  • If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file.
  • Now, type ./a.out to execute your program.
  • You will see the output "Hello World" printed on the screen.
$ gcc hello.c
$ ./a.out
Hello World
You can also specify an out file with -o option
$ gcc -o hello hello.c 
$ ./hello
Hello World
 
Make sure the gcc compiler is in your path and that you are running it in the directory containing the source file hello.c.

GCC Compiler Options
1. Specify the Output Executable Name
Use option -o, as shown below, to specify the output file name for the executable.
$gcc hello.c -o hello
The command above would produce an output file with name ‘hello’.

2. Enable all warnings set through -Wall option
This option enables all the warnings in GCC.
$gcc -Wall hello.c

3.Produce only the preprocessor output with -E option
The output of preprocessing stage can be produced using the -E option.
 $gcc -E hello.c > hello.i

4. Produce only the assembly code using -S option
The assembly level output can be produced using the -S option.
$gcc -S hello.c > hello.s

5. Produce only the compiled code using the -C option
To produce only the compiled code (without any linking), use the -C option.
$gcc -C hello.c
The command above would produce a file hello.o that would contain machine level code or the compiled code.

6. Produce all the intermediate files using -save-temps function
The option -save-temps can do all the work done in example 4,5 and 6 above. Through this option, output at all the stages of compilation is stored in the current directory. Please note that this option produces the executable also.

For example :
$gcc -save-temps hello.c 
$ls
a.out hello.c hello.i hello.o hello.s

So we see that all the intermediate files as well as the final executable was produced in the output.

7. Link with shared libraries using -l option
The option -l can be used to link with shared libraries.
For example:
gcc -Wall hello.c -o main -l libCPPfile
The gcc command mentioned above links the code hello.c with the shared library libCPPfile. So to produce the final executable ‘hello’.

9. Print all the executed commands using -v option
The option -v can be used to provide verbose information on all the steps gcc takes while compiling a source file.
For example :
$gcc -Wall -v hello.c -o hello

10. Provide gcc options through a file using @ option
The options to gcc can also be provided through a file. This can be done using the @ option followed by the file name containing the options. More than one options are separated by a white space.

Here is an example :
$cat opt_file
 -Wall -o hello
The opt_file contains the options.

Now compile the code by providing opt_file along with option @
$gcc main.c @opt_file

Note: You can also do programs online....try https://www.onlinegdb.com/




Comments

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar

Arrays in C-single and multi dimensional arrays- list and matrix

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list(vector); A two dimensional array is like a table(matrix). We can have more dimensions. Always, Contiguous (adjacent) memory locations are used to store array elements in memory. Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element. Declaring  Single Dimensional Arrays Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for mentioning dimension of the array.  Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.  In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allo