Beginners guide to GCC

From GLUG-BOM

You are here: Main Page >> Howtos >> Beginners guide to GCC

Contents

Introduction

This guide is a How-to that would serve the purpose of instructing the reader (novices, newbies: typically) to use the GCC. Often, GCC is assumed to be an acronym for GNU 'C' Compiler, which is wrong. This is because, it is an acronym for GNU Compiler Collection. The reason is that GCC is capable of compiling 'C', 'C++', 'Objective-C' (similar OO feature added to 'C'), 'Java' etc. with associated library files. GCC is usually the default 'C' compiler under most distributions. The Linux kernel's first version, was compiled with GCC. It is most widely used for C and C++ programs.

Installing GCC

It is assumed that you (the reader) are aware of your distro's package management software for installing / uninstalling software. I'll describe a method for installing GCC on Ubuntu.

The Compiler collection

Under Ubuntu, open a terminal and type

sudo apt-get install gcc

This will list the associated files and ask for confirmation of the proceeding the download and installation of GCC. If the installation is successful, one can type

gcc

at a terminal to test. This will return with

gcc: no input files

Libraries

Secondly, one might need libraries for compiling C, C++ programs. Under Ubuntu, one would have to install several packages for it, if not already installed, which is the case with the default installation of Ubuntu (or its derivatives)

For identifying the latest package of the libraries available for your distribution version, issue the command

(for C libraries)

apt-cache search libc* | more 

(for C++ libraries)

apt-cache search libstdc++ | more 

(for C libraries)

sudo apt-get install libc6 libc6-dev 

(for C++ libraries)

sudo apt-get install libstdc++6 libstdc++6

Also, one might have to install the package,

sudo apt-get install build-essential

After installation, please check the /usr/include folder for files such as "stdio.h", "stdlib.h" etc. (ANSI C standard header files)

Using an editor to write your first C program

You can use your favourite text editor to write this program. GNU Nano is a text editor for the Konsole and Kate is a GUI (KDE) based editor. (Type, 'nano' for Konsole based editor or 'kate' at the terminal to fire up the editor)

In Gnome,you can use Gedit(GUI) text editor to program or nano for a editor in terminal(Equivalent of Konsole in KDE,found in Applications>>Accessories>>terminal).You can type gedit at the terminal to fire up Gedit or alternatively if you're a GUI fan,you can find Gedit in the Applications menu under Applications>>Accessories>>Text Editor.(Ubuntu 7.04)

Below is a simple program that prints numbers from 1 to 10 (barring from typical "Hello World" program). Assuming that you already know how to program in C and have some (even little) experience in programming under Windows, the following program should be easy to understand.

#include<stdio.h>

int main(void){ 
     int counter; // Variable to loop from one to ten
     
    //The following loop will print numbers in a line from one to ten
     for(counter = 1; counter<11; counter++)
          printf("%d ", counter);
     
     return 0;
}
//main ends <return>

Let us name it as firstcprog.c

Please note, if you have programmed in TurboC++ 3.0 you would typically be used to typing void main(). Note 'void' is the return type of the main() function. GCC requires that programmers specify an integer return type for main function, though this is not mandatory. However, GCC will compile the program and also generate a warning message informing that the return type of main is not 'int'.


Also note the <return> at the end. Always, insert a new line at the end of every C / C++ program that you write (required by GCC).

Compiling your first C program

We'll see the easier way to compile the program and generate an output file (for execution to see the results). However, a bit of theory is required before we proceed. That'll help to understand the options provided by GCC.

Understand the process of Compilation

Building an executable from a C program involves multiple steps. The first step is that of invoking the compiler. This means, when gcc is typed at the prompt with the argument as a 'C' source code file, the C compiler of GCC is invoked. Second, the preprocessor (one that processes lines such as #include<stdio.h>, #define, #ifdef etc.) is invoked to do preprocessing. Later, the program is then checked for compile-time errors such as missing semicolons, typos etc. and an assembly code pertaining to the specific CPU architecture is generated. Once the source code is free of errors, an object code is generated. An object code is typically code generated for the specific target CPU(the one on which the executable is required to run). Next, the linker is invoked to create an actual executable file.

A simple example of what linker would do, is this. The printf statement in a C program, is a function whose definition is available within the standard C library. The linker associates the code of printf to be included as instructions in the executable file instructing the computer to execute the code as defined in printf.

Commands to compile and execute the program

The command to compile a C / C++ program is as follows

gcc <filename.c>

Therefore, for your first program, you'll issue the following command at the terminal.

gcc firstcprog.c

This will generate an ouput file named a.out (automatically). This is the default file created for any compiled C / C++ file.

To run the program, we issue the command

./a.out 

The dot and slash (./) preceeding the output filename is used to indicate that the output file resides in the current directory.

A section below describes advanced options for GCC to compile programs, generate user-defined / custom names for output files, see the amount of CPU time consumed, take note of different warning messages generated and more.

Write your first C++ program

Writing C++ is a little different when using g++ as compared to Turbo C++ 3.0. However, with basic knowledge of C++ and STL (Standard Template Library), writing C++ programs for g++ should not be difficult for you. Below is a sample C++ program. As explained earlier, you can start your favourite text editor and type the following program. The commands to compile and execute the program are given below.

#include<iostream>
#include<string>

using namespace std;

class firstprg{
	private:
          string name;

	public: 
		 //Parameterized constructor
		 firstprg(string nm){
			 name = nm;
		 }

 		 //Member function
		 void display(){
			 cout<<"Hello "<<name<<endl;
		 }
};

int main(void){
	string nm;
	cout<<"Enter your name: ";
		cin>>nm;

	firstprg obj(nm); // Calling the parameterized constructor of class
	obj.display();
	return 0;
}


Allow a newline after the closing brace of main method. Let us name it firstcppprog.cpp

Note 1: The minor difference of using the standard namespace, std.

Note 2: It's preferable to use the statement using std::cout; and using std::cin; if only cout and cin are mostly used in your program rather than using using namespace std; which makes all the symbols in the std namespace available without qualification.

Commands to compile and execute C++ program

Though one can use the same "gcc commands" to compile C++ (gcc summons the appropriate compiler) , g++ is a traditional nickname for GCC's C++ compiler. Get into the environment of C++ ;).

Therefore to compile any C++ file, issue the following command at the terminal

g++ <filename.cpp>

For our program, it would be

g++ firstcppprog.cpp

which would generate the same output executable file, a.out. Note that this file is generated only if the program is free from compile-time errors.

To execute the program, at the terminal, type

./a.out

See the section on Options for details on generating a different output file for each file. (Hint: see the -o option)

Options with GCC

GCC provides a number of options while compiling a source file. The options explained here are ones that the author uses. (As time progresses, and with collaborative edits, other options with explanations would come up).

1. -o filename

The above option is used to specify an output filename to GCC.

For example, when one types

gcc -o <output_filename.out> <filename.c>

the -o option, followed by an output file name, would cause the generated output file to be named output_filename.out (here an executable code) instead of the default a.out. The last argument above specifies the source code file to compile. It is recommended that this option be used to name executables meaningfully while compiling C programs.

This option can be combined with other options to name the output files of the preprocessor, compiler, assembler among others.

Note:

The output filename should be specified immediately after the -o character (spaces are permitted).
The extension of the file, need not be .out (or anything specific) but could be .out for obvious reasons.

2. -c

The -c option, instructs gcc to compile the files and generate an object file. This means, the linker isn't invoked and no linking is done. Therefore, the output compiling with a -c option, for example, such as

gcc -c <filename.c>

would be an object file by the name <filename.o>

3. -S

The -S option, instructs gcc to generate an assembler code. The output of compiling with a -S option, would lead to creation of an assembler code with x86 based instruction sets. (or depending on the machine type). For example,

gcc -S <filename.c> 

would generate an object file named, <filename.s>, which will have assembler code.

4. -E

The -E option would result into generating a file after pre-processing. The output is a pre-processed code. For example,

gcc -E <filename.c> 

would display the pre-processed source code on to the terminal.

5. -Wall

The above option enables many types of warning messages and helps point out common errors.

6. -v

This option instructs gcc to show the exact steps followed to create the executable from the source code. The output details the steps explained in Understand the process of Compilation

gcc -v <c-source-file>