Sunday, December 6, 2009

GCC - How To Create a Static and Dynamic Libraries/ Characterstics of Static and Dynamic Libraries/ Using Static or Dyanmic Libraries

Topic is called writing libraries.
I will be covering creating and using static and shared libraries. (Yes using too, because that is the main part)
So here is simplest you can do
I will write two files containg a function each, write one header file and use those function in a prog.
Go into some directory
create a dirctory called "incl" this is the place where your manual created header files will be searched.

go to "../incl" create a header file called "myheader.h" and write folloing lines there

#include"stdio.h"
extern void one();
extern void second();

save it... Thats it, your header file is ready.

Now the second part is to create library......Ok there are 1001 documents on net which explains you what a lib does and all that blah blah.. I will just focus here how to create a library.
First I am going to create a static library.

come to base dir and create a dir called "mylib"
Go to mylib dir and create two .c files

first.c
return type one()
{
print("\nThis is from the first libraray\n");
}


second.c

return type second()
{
print("\this is from the second library\n");
}


now just compile these files ( you can not create a executalbe as there is no main funciton here)

gcc -c first.c -o first.o
gcc -c second.c -o second.o


Now you have two objects file with you.
You want to create the static lib.
Ok to be very frank static lib is nothing but puting the all the concerned object files in a single file.
Nothing more. This is done by

1) ar rcs libfirstlib.a first.o second.o

This command is just like ar (archiving the many object files into one )

Now few points to be noted here, your lib must start with "lib" prefix and extension for static is .a.


2) To just make indexing fast in the lib, you CAN (that is it may or may not be needed lib will work even without it)

ranlib libfirstlib.a


Thats it your static lib is ready.



Now comes the part of using this lib and header file into your program.
Come to the base lib again

//use.c
include file "mylib.h"
include file
main function come here()
{
one();
second();
prin("\nBoht of the lib funcitons called .....\n");
}


Write one program here using the lib function and include the header file you have crated.

Ok the thing is simple your compiler and linker don't know anything about where is your .h file which you have included in your program.. nor linker will know anything about the fucntion defination.

So how to do it.

Here is the logic

when compling and linking ( as you know " gcc file.c" is equivalent to compling and linking if you do not want to link you use "gcc -c")..you need to give the header file and lib path where preprocessor and liker will look for.

By default preprocessor will look in some directory (defined differnetlly form sys to sys)
Gen it is /use/include

and lib in /use/lib

Now suppose you do not have premission to write there and location of you header file and lib is different then use this.


gcc -I ./inclu/ -L ./mylib/ -static use.c -lfirstlib


Thic command will do.

-I tells where to look for a header file

and -L about the lib file.


Note you can also copy .h to /usr/include and .a to /usr/lib dir it will work.


So I explained all the synario here about static lib.



Now its turn of shared library. And guess what Shared library I have created is not working. Will post this some time later.

Very Useful links to read are mentioned below

http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html

http://www.gpres.org/tutorials/shared.xhtml

http://gcc.gnu.org/ml/gcc/1999-12/msg00092.html

http://www.iram.fr/~roche/code/c++/c++_AddNumbers.html

http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html

http://randu.org/tutorials/c/libraries.php

http://randu.org/tutorials/c/

Tuesday, December 1, 2009

Semaphores

Semaphores

When They are used
Semaphores are used for two purposes
1) Process Synchronization
2) Critical Section problem

Is there any alternative to Semaphores
Yes there are few solutions know as n process synchronization(software solutions) and Hardware solutions. Hardware solutions becomes complicated when number of process increases and secondly in all these you have busy waiting (it means you are eating CPU cycles when waiting and no other productive work can be done during this). So practically they are never used

What are they
They are synchronization tool. In a very abstract term semaphore is a global variables, which apart form initialization can be modified by only two operations wait() and signal().

Suppose S is semaphore
where wait is as simple as
wait(s)
{
while(s<=0)
; //do no operation
s--;
}

signal(S)
{
S++;
}

Why not Global Variables
Now if this was the only criteria you can simply use global variables and can write above mentioned functions in your C code to create semaphores. But its not that simple in addition to above things we need to ensure
1) Modification of S value must be done exclusively.
2) In addition checking of while(s<=0) in wait and possible modification S--, should also be done without interruption
3) Above implementation is having busy wait too

Example of Usage

1) n process critical section problem
put every process code like this
do {
wait (mutex);
critical section;
signal(mutex);
reminder section;

}while(1);

2) Synchronization
we can also use this for synchronization. e.g two concurrent process P1 and P2 having statements S1 and S2. We want in any case S1 should execute first. this can be achieved easily by
initialize S=0;
in P1 in P2
S1; wait(S);
signal(s); S2;

Implementation

The very basic implementation which I showed above has one problem they also have busy waiting. This is not at very appreciated in multiprogramming environments where wasting CPU is crime equivalent to murdering someone. These type of semaphores are called the spinlock semaphores.

But these semaphore have advantage too. There is no context switch required when process wait on Semaphore. Hence if waiting time is minimal this approach is very helpful.

How to overcome busy waiting.
you can modify wait and signal. when every you have to wait instead of looping you can block the current process. Bock is very common system call present in every Operating system.
in signal you simple call wakeup() for that process.
You also have to make sure that you maintain queue for all blocked process (i think list of PCB will do it)
There is one more important point on wakeup you are simply putting it on ready queue of Short term (or CPU scheduler).. its up to CPU scheduler scheduling policy when that process will be executed.


Critical Section Problem of Semaphore implementation
This is critical aspect of semaphore implementation that they are executed atomically. We must guarantee that no two processes can execute wait and signal operations on the same semaphores at same time. This is called critical section problem and can be solved in 2 ways

1) In uniprocessor environment we can simply inhibit (disable) interrupts during the time that wait and signal operations are executing. This works very well in uniprocessor env because, once interrupts are inhibited, instructions from different processes can not be interleaved.

2)In multiprocessor env inhibiting of interrupts does not work. Instructions from different processes many be interleaved income arbitrary way. We can employ any software solutions (not discussed here) for critical section problem, where critical section consists of wait and signal procedures(remember there it was modification of files, global variable etc). It must be admitted here that we are still using buy wait here but at least that is only on wait and signal and not on full process.

Monday, June 15, 2009

Scope/Life Time

Ok to set the things straight

there are three kind of scope ( place in the code where variable can be accesed )

extern : entire prog
auto : in the block where its defined.
static : now there is a nice twist here in words. I will say if defined inside a funtion it has a auto scope.
But it you define it before a function then it has a scope there after but only in the file where its defined.


Now its life time utill when variable is having life.... fundu haan :)

Not like that it simply means that point of time when variable can be accessed.

Unfortunatly there is no keyword as scope to define life time.

Life time of static and extern variable is before main is called and utill program exits.
Life time of arguments and that of local variables it is from the point when funciton is called and untill function return.
Life time of dynamic allocated block is from the point when we issue malloc or calloc command to the point when we use free call.

Why Do we Require Segments in C/C++ Language

Why to have many segments in a ELF file?

This can be easily explained why number of storage classes available in C language and some basic computer Science knowledge.

Code Segment

When we compile code we will get binary language code. These are the instructions to the processor what to do.

So to execute any program you need these instructions. These instructions will not change throughout you program. Processor needs to have these instruction in the RAM or in some cases of embedded system they can be directly read form the ROM (if byte addressable). That’s the reason to put them in a segment called Code or Text segment. Before executing the program this segment is copied to RAM and program starts executing by reading these instructions.

Data Segments (initialized variables)

C has provided global variables (for the time being consider initialized variables). Why to use global variable? Answer is very simple we want to have variable visible to entire program/file and more importantly they will retain their values throughout the program. Aren’t they required in RAM for full life span of program? Yes that’s why placed in the segment called data segment. Data segment is part of the object file as well as executable.

Initialized Static variables also has behavior they stay alive full span of program so are also placed in the data segment.

BSS (Un- initialized Static/Global Variable)

Ok you want global variable but its not being initialized. As it doesn’t have any value associated till run time, why to waste the space in the object file/ executable. That’s the reason there is one more segment made called block started by symbol BSS where just the information about these kind of variable is stored. At run time appropriate memory is allocated to these types of variables.

Read Only data Segment

I something is const, how does file format will ensure that modification of such kind of data is prohibited and if you try to do so; compilation/runtime error is resulted. Very easy, file format store such kind of variables in a region which is read only. You can only modify the region value one time and that is during initializing. So all the constants, string literals are stored in this read only segment.

Heap Memory and Stack Memory

These are not the part of the executable/ object file. These are run time entities.

Where Const Variables are stored

Yeah this is very important question and to answer it in one sentence will be “implementation dependent”. Now one thing should be clear and that is difference between constant and read-only. To be honest term “constant variable” is oxymoron. Data can be constant a object can’t. Its pretty obvious if entity changes its value then that’s not a constant.

A variable can have cont qualifier in that case its just marked as read only. As I have told in one more post also “adding const qualifier to a variable is promises you make that variable will not change its value and it’s up to the compiler to keep this promise”. Const variable is marked as read only but there are still ways to breach that read-only hindrance. Want to have a proof in “C”

Look at this

Cont int a =20;

int *p=(int *)&a;

a=30; //Compilation erro

but

*p =30; will get through.

If you have noticed the above few lines carefully you can make out that const variables are not stored in rodata segment. They will go to stack only (if local).

Making any variable const does not change the place where variable is stored.

Register Variables

Register variable ;

Its simply a request to the compiler that perticular variable will be used heavly and place it in CPU registers.

But there are lots of gotchas here

1) Which data can be held in registers depend on register size. Normaly its size of word or interger elemnet max. Though some system do have the registers capalbe of holding the floating point values in registers.

2) Though its a request but once you declare a variable as register it may go to the register. So you cannot use its address in your program. It means you can not use & operator on the register variable. If you try to do the same you are welcomed with compiler error.


3) More over you declared a variable regiter and system choose to put it in the register. It may actually slow down your system. Because no of registers are limited in numbers and you have reserved some of them, now the variable you have placed in the register is not modifying enough so its like wasting a resource.


4) You can ask when to use register type. Plain answer is never.
In earlier days it was a value addtion to the 'C' language as earlier compiler were not using register at all implicitly.
But mordern compilers are smart enough to decide which value is to be placed where. Actully its a rare event that by putting some value in register can increase the efficeny of your program.

Some of todays compiler simply ignore the register keyword as its perfecly inline with reiger definition "Its a request not an order".

Static Vs Dynamic Ram

What is the difference between static RAM and dynamic RAM?

Inside this Article

1. What is the difference between static RAM and dynamic RAM?

2. Lots More Information

3. See all Memory articles

Computer Videos

* More Computer Videos »

capacitor
A capacitor stores electrons in computer memory cells. The memory must then be refreshed or flip-flopped.

­Your computer probably uses both static RAM and dynamic RAM at the same time, but it uses them for different reasons because of the cost difference between the two types. If you understand how dynamic RAM and static RAM chips work inside, it is easy to see why the cost difference is there,­ and you can also understand the names.

Dynamic RAM is the most common type of memory in use today. Inside a dynamic RAM chip, each memory cell holds one bit of information and is made up of two parts: a transistor and a capacitor. These are, of course, extremely small transistors and capacitors so that millions of them can fit on a single memory chip. The capacitor holds the bit of information -- a 0 or a 1 (see How Bits and Bytes Work for information on bits). The transistor acts as a switch that lets the control circuitry on the memory chip read the capacitor or change its state.

A capacitor is like a small bucket that is able to store electrons. To store a 1 in the memory cell, the bucket is filled with electrons. To store a 0, it is emptied. The problem with the capacitor's bucket is that it has a leak. In a matter of a few milliseconds a full bucket becomes empty. Therefore, for dynamic memory to work, either the CPU or the memory controller has to come along and recharge all of the capacitors holding a 1 before they discharge. To do this, the memory controller reads the memory and then writes it right back. This refresh operation happens automatically thousands of times per second.

This refresh operation is where dynamic RAM gets its name. Dynamic RAM has to be dynamically refreshed all of the time or it forgets what it is holding. The downside of all of this refreshing is that it takes time and slows down the memory.

*

Static RAM uses a completely different technology. In static RAM, a form of flip-flop holds each bit of memory (see How Boolean Gates Work for detail on flip-flops). A flip-flop for a memory cell takes 4 or 6 transistors along with some wiring, but never has to be refreshed. This makes static RAM significantly faster than dynamic RAM. However, because it has more parts, a static memory cell takes a lot more space on a chip than a dynamic memory cell. Therefore you get less memory per chip, and that makes static RAM a lot more expensive.

So static RAM is fast and expensive, and dynamic RAM is less expensive and slower. Therefore static RAM is used to create the CPU's speed-sensitive cache, while dynamic RAM forms the larger system RAM space.

Saturday, January 17, 2009

Sum of two numbers without using plus operator

#include
int main()
{
int a=3000,b=20,sum;
char *p;
p=(char *)a;
sum= (int)&p[b]; //adding a & b
printf("%d",sum);
return 0;
}
How this code is working than start from the statement p=(char *)a;
Here you are assigning the value of a to p means p will be pointing at location address equivalent to p
So for the above example
p=3000
Now sum=(int )&p[b];
For this case here p[b] is equivalent to (p+b) because you are using char pointer as p if it is other pointer type than it will be equivalent to (p+(size of data type) * b)
So the statement becomes like this
Sum=(int)&(p+b)
Because p is pointer so you need & to assign it to a variable and int is used to change the value into integer.
So you get a+b in the sum.