Saturday, May 31, 2014

How to create c++ header files and make them work in ubuntu

You can easily create header files in c++ and work with them using an IDE(Integrated Development Environment) such as CodeBlocks, Eclipse, etc. If you are using an IDE, you just need to create the relevant files( such as header file, implementation file and main file) and compile them directly using the IDE. so when you give the compile command  the IDE care the rest of the tasks and give you the output.

But if you are going to do this task in a terminal(ubuntu) without using any IDE then you will have to do these all the steps done by the IDE manually. Therefore here is explained how the same thing can be done by using terminal.(only the steps are shown and not in much details)

step 1 :

You need to create the header file as you need
(a sample header file is shown below)

// rectangle.h  (begining of the file)

#ifndef _RECTANGLE_H
#define _RECTANBLE_H

double area(int length, int width);
// initialize any functions as you need

// end of the file

you need to save this as a header file.(rectangle.h)

step 2 :

Now you need to create the implementation file.
(a sample implementation file is shown below)

//rectangle.cpp (begining of the file)

#include <iostream>
#include "rectangle.h"

using namespace std;

double area(int length, int width){

    return length*width;


// end of the file

you need to save this file as a c++ file (rectangle.cpp)

step 3 :

Now you need to create the main file
(a sample main file is shown below)

// main.cpp  beginning of the file

 #include <iostream>
#include "rectangle.h"

int main(){

    std::cout<< area(4,4);

    return 0;


// end of the file

you need to save this file as a c++ file (main.cpp)

step 4 :

Now you can run these files on terminal.

put all the above 3 files into a same folder. then open terminal and go to the folder where these 3 files reside. (using "cd" command   eg : "cd Desktop\header_test_folder")

first you need to compile all c++ files.
type bellow command for each c++ file

g++ -c filename.cpp
 //other cpp files (if any)
g++ -c main.cpp

example : (for above files)

g++ -c rectangle.cpp
g++ -c main.cpp

now you need to link these files and create the executable file.
so you need to run below command for that.

g++ -o finalfilename main.o filename.o  // otherfiles.o (if any) 

example : (for above files)

g++ -o finalrectangle main.o rectangle.o

now you can see there is a new file in your directory(finalfilename)
you need to run that file


for above example


now it will be running on the terminal.

No comments:

Post a Comment