Monday, May 19, 2008

Building C++ programs in Linux

This is very basic guide for getting anyone started with building and debugging C/C++ code in GDB.

I will put forth information about building in Linux. The best reference book for this is "Advanced Linux Programming" which is available for free

http://www.advancedlinuxprogramming.com


Building your own C++ code in linux.
I will take code sample which my friend Hari used while giving us GDB training sessions. He used the following code to explain us the way to use GDB for debugging.

list.h:-

#ifndef __LLIST_HEADER_INC__
#define __LLIST_HEADER_INC__

//////////////////////////////////////////////////////////////////////
#include
//////////////////////////////////////////////////////////////////////
// class LinkedList definition begins

class LinkedList
{
struct LLItem
{
int value;
struct LLItem *next, *prev;
};

public:
LinkedList ();
~LinkedList ();

void push (int val);
int pop ();
size_t size () { return m_iSize; };

private:
LLItem* m_pFirstNode, *m_pCurNode;
size_t m_iSize;
};

#endif // __LLIST_HEADER_INC__


List.cpp:-
#include "list.hpp"

//////////////////////////////////////////////////////////////////////
// class LinkedList implementation begins

LinkedList::LinkedList ()
: m_pFirstNode(NULL), m_pCurNode(NULL)
{
}

LinkedList::~LinkedList()
{
m_pCurNode = m_pFirstNode;
LLItem* tnode;
while (m_pCurNode)
{
tnode = m_pCurNode->next;
delete m_pCurNode;
m_pCurNode = tnode;
}
m_pFirstNode = NULL;
m_pCurNode = NULL;
}

void LinkedList::push (int val)
{
LLItem* cnode = m_pFirstNode;
while (cnode && cnode->next)
{
cnode = cnode->next;
}

LLItem* tnode = new LLItem ();
tnode->value = val;
cnode->next = tnode;
tnode->prev = cnode;
tnode->next = NULL;

++m_iSize;
}

int LinkedList::pop ()
{
LLItem* cnode = m_pFirstNode;
while (cnode && cnode->next)
{
cnode = cnode->next;
}

int value = cnode->value;
LLItem* pnode = cnode->prev;
pnode->next = NULL;
delete cnode;
--m_iSize;

return value;
}

// class LinkedList implementation ends
//////////////////////////////////////////////////////////////////////

Main.cpp:-
#include "list.h"
#include
#include

int
main ()
{
LinkedList* ll = new LinkedList ();
size_t list_size = 100000;
for (size_t i = 0; i < list_size; ++i)
{
ll->push (random ());
}
for (size_t i = 0; i < list_size; ++i)
{
std::cout << "Popped element " << ll->pop () << std::endl;
std::cout << "The current size is " << ll->size () << std::endl;
}
return 0;
}




The above code is linked list code. It's a buildable code however on execution, it will give segmentation fault. I have placed the code in my $HOME/LinkedList area. The files present are main.cpp, list.h and list.cpp


Creating Object File.

The C++ compiler is called g++ while a C compiler is called gcc. The method of operating is very similiar. Suppose you have main.c, then to compile it, following is the command

% gcc -c main.c

To compile a C source file, you use the -c option. The resulting object file is named main.o.

To compile c++ file we use g++ in similiar way

% g++ -c list.cpp

The -c option tells g++ to compile the program to an object file only; without it, g++ will attempt to link the program to produce an executable. After you’ve typed this command, you’ll have an object file called list.o. Similiarly

Some other options are required when building large applications. The -I option is used to tell GCC where to search for header files. By default, GCC looks in the current directory and in the directories where headers for the standard libraries are installed. If you need to include header files from somewhere else, you’ll need the -I option.

In our case if we have kept out main.cpp in the $HOME/LinkedList area and placed our list.hpp in $HOME/LinkedList/Include area then we need to include the path of .hpp file while building.

% g++ -c -I ../include list..cpp

Note:- On doing "pwd" at prompt, It should display path $HOME/LinkedList

If you’re really building production code, you probably want to have GCC optimize the code so that it runs as quickly as possible.You can do this by using the -O2 command-line option. (GCC has several different levels of optimization; the second
level is appropriate for most programs.) For example, the following compiles list.cpp with optimization turned on:

% g++ -c -O2 list.cpp


Linking Object Files

Now we have objects of both main.cpp and list.cpp. One should always use g++ to link a program that contains C++ code, even if it also contains C code. If your program contains only C code, you should use gcc instead.
We link our code in following manner.

% g++ -o llist main.o llist.o

The -o option gives the name of the file to generate as output from the link step. g++ automatically links in the standard C runtime library containing the implementation of standard functions which have been used in code like cout, cin..... If one needs to link in another library, you would have to specifically link those library's with -l option. In Linux, library names almost always start with lib. For example, the Pluggable Authentication Module (PAM) library is called libpam.a. To link in libpam.a, you use a command like this:

% g++ -o llist main.o llist.o -lpam

The compiler automatically adds the lib prefix and the .a suffix. As with header files, the linker looks for libraries in some standard places, including the /lib and /usr/lib directories that contain the standard system libraries. If one wants the linker to search other directories as well, one should use the -L option, which is the parallel of the -I option. For example.

% g++ -ollist main.o llist.o -L/usr/local/lib/pam -lpam

Although you don’t have to use the -I option to get the preprocessor to search the current directory, you do have to use the -L option to get the linker to search the current directory. In particular, you could use the following to instruct the linker to find the test library in the current directory:

% gcc -o llist main.o llist.o -L. -ltest

Automated Object Building and Linking using Makefile.

The basic idea behind make is simple.One tells make what targets you want to build and then give rules explaining how to build them. One also specify dependencies that indicate when a particular target should be rebuilt. In our case, we have three target:- main.o, list.o and and llist.

Our llist depends upon our list.o and main.o. So for linking and creating our executable files, we need those two objects already created. Also the object files should be rebuilt whenever the corresponding source files change. On top of it, changes to the header file should result in all the source files including it to be rebuilt. In our case list.hpp also should cause both of the
object files to be rebuilt because both source files include that header file.

Also one might want to remove previously created object files and programs and then start fresh built. The rule
for this target uses the rm command to remove the files.

Here’s what Makefile contains:

llist: main.o list.o
g++ $(CFLAGS) -o llist main.o list.o

main.o: main.c list.hpp
g++ $(CFLAGS) -c main.cpp

list.o: list.cpp list.hpp
g++ $(CFLAGS) -c list.cpp

clean:
rm -f *.o llist


You can see that targets are listed on the left, followed by a colon and then any dependencies.
The rule to build that target is on the next line. The line with the rule on it must start with a Tab character, or make
will get confused.

If one types only

% make

on the command-line, you’ll see the following:
% make
g++ -c main.cpp
g++ -c list.cpp
g++ -o llist main.o list.o


You can see that make has automatically built the object files and then linked them. If you now change main.cpp in some trivial way and type make again, you’ll see the following:

% make
g++ -c main.cpp
g++ -o llist main.o list.o


Following command will clean the object files

% make clean
rm -f *.o llist


The $(CFLAGS) is a make variable.You can define this variable either in the Makefile itself or on the command line. GNU make will substitute the value of the variable when it executes the rule. So, for example, to recompile with optimization enabled, you would do this:

% make CFLAGS=-O2
g++ -O2 -c main.cpp
g++ -O2 -c list.cpp
g++ -o llist main.o list.o


For debugging with GDB, one will have to compile with debugging information enabled. Do this by adding the -g switch on the compilation command line. So we build using -g flag in makefile

% make CFLAGS=-g
g++ -g -c main.cpp
g++ -g -c list.cpp
g++ -g -o llist main.o list.o


When one compiles with -g, the compiler includes extra information in the object files and executables.The debugger uses this information to figure out which addresses correspond to which lines in which source files, how to print out local variables, and so forth.


Programming Ring - New Post
Programming Ring - Old Post

19 comments:

Anonymous said...

[u][b]Xrumer[/b][/u]

[b]Xrumer SEO Professionals

As Xrumer experts, we possess been using [url=http://www.xrumer-seo.com]Xrumer[/url] for a sustained fix conditions and grasp how to harness the massive power of Xrumer and turn it into a Spondulix machine.

We also purvey the cheapest prices on the market. Diverse competitors devise expect 2x or even 3x and a end of the continuously 5x what we debt you. But we have faith in providing enormous accommodation at a tearful affordable rate. The unbroken direct attention to of purchasing Xrumer blasts is because it is a cheaper surrogate to buying Xrumer. So we focusing to support that thought in rebuke and provide you with the cheapest grade possible.

Not just do we have the greatest prices but our turnaround heyday after your Xrumer posting is super fast. We drive secure your posting done before you certain it.

We also provide you with a ample log of loaded posts on contrary forums. So that you can catch a glimpse of over the extent of yourself the power of Xrumer and how we be struck by harnessed it to help your site.[/b]


[b]Search Engine Optimization

Using Xrumer you can expect to realize thousands upon thousands of backlinks exchange for your site. Tons of the forums that your Site you intent be posted on have acute PageRank. Having your association on these sites can truly help build up some cover grade back links and uncommonly boost your Alexa Rating and Google PageRank rating utterly the roof.

This is making your position more and more popular. And with this developing in regard as superbly as PageRank you can expect to appreciate your area definitely downright high-pitched in those Search Engine Results.
Above

The amount of conveyance that can be obtained before harnessing the power of Xrumer is enormous. You are publishing your locality to tens of thousands of forums. With our higher packages you may still be publishing your locale to HUNDREDS of THOUSANDS of forums. Ponder 1 post on a popular forum disposition usually cotton on to a leave 1000 or so views, with communicate 100 of those people visiting your site. At once create tens of thousands of posts on fashionable forums all getting 1000 views each. Your freight liking function through the roof.

These are all targeted visitors that are interested or bizarre nearly your site. Deem how divers sales or leads you can succeed in with this considerable gang of targeted visitors. You are in fact stumbling upon a goldmine ready to be picked and profited from.

Remember, Transport is Money.
[/b]

BECOME ENTHUSIASTIC ABOUT YOUR TWOPENNY DEFAME TODAY:


http://www.xrumer-seo.com

Anonymous said...

Predilection casinos? scrutinization this untested [url=http://www.realcazinoz.com]casino[/url] captain and seize up online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also search into our additional [url=http://freecasinogames2010.webs.com]casino[/url] orientate at http://freecasinogames2010.webs.com and recompense in crap compressed dough !
another the social conventions [url=http://www.ttittancasino.com]casino spiele[/url] locality is www.ttittancasino.com , in convalesce german gamblers, scion in manumitted online casino bonus.

Anonymous said...

Someone deleted several links from badongo and uploading servers.

From now, we will use www.tinyurlalternative.com as our default [url=http://www.tinyurlalternative.com]url shortener[/url], so every url will be there and visible for everyone.

You can choose from many great [url=http://kfc.ms]short url[/url] names like:

kfc.ms easysharelink.info jumpme.info megauploadlink.info megavideolink.info mygamelink.info myrapidsharelink.info mytorrentlink.info myurlshortener.com mywarezlink.info urlredirect.info urlshrinker.info weblinkshortener.com youtubelink.info and many others.

They include above 60 other ready domains and the [url=http://myurlshortener.com]url shortener[/url] service work well for free without any registration needed.

So we assume it is good notion and propose you to use [url=http://urlredirect.info]url redirect[/url] service too!

Thank you.

Anonymous said...

Making money on the internet is easy in the hush-hush world of [URL=http://www.www.blackhatmoneymaker.com]blackhat hosting[/URL], You are far from alone if you don't know what blackhat is. Blackhat marketing uses alternative or misunderstood methods to produce an income online.

Anonymous said...

I give birth to interpret a insufficient of the articles on your website in the present circumstances, and I really like your tastefulness of blogging. I added it to my favorites trap page roster and will be checking back soon. Will report register out of order my site as highly and fail me be familiar with what you think. Thanks.

Anonymous said...

buy viagra buy viagra online now - does viagra work if you have low testosterone

Anonymous said...

buy tramadol online usual dosage tramadol - buy tramadol online overnight shipping

Anonymous said...

soma price soma 350 mg info - buy soma online with credit card

Anonymous said...

buy soma online what is generic soma - soma online texas

Anonymous said...

buy soma soma san diego sports arena - buy soma mastercard

Anonymous said...

generic xanax xanax effects elderly - buy xanax xr online no prescription

Anonymous said...

generic xanax xanax 1 mg at a time - xanax side effects next day

Anonymous said...

buy tramadol overnight cod tramadol overdose dosage - buy tramadol online eu

Anonymous said...

cialis professional cialis online apotheke - buy cialis online us

Anonymous said...

http://landvoicelearning.com/#63987 buy tramadol online yahoo - tramadol online us

Anonymous said...

buy klonopin online klonopin side effects withdrawal symptoms - klonopin side effects pdr

Anonymous said...

learn how to buy tramdadol tramadol 50 mg for humans - tramadol dosage greyhounds

Anonymous said...

learn how to buy tramdadol tramadol 50 mg reviews - can you buy tramadol usa

Anonymous said...

http://buytramadolonlinecool.com/#63102 tramadol hcl 10 mg - tramadol dose for 40 lb dog