Archive for May 2012
MOUSE POINTER IN C(USING GRAPHICS)
#include<dos.h>
#include<graphics.h>
#include<alloc.h>
#include<conio.h>
#include<stdio.h>
char *menu[]={"samosa","sambharwada","dahiwada","exit"};
union REGS i,o;
main()
{
int gd=DETECT,gm,choice=1,bill=0,width=0,i,count;
char **buffer;
initgraph(&gd,&gm,"c:\\tc\\bgi");
if(initmouse()==0)
{
printf("\n unable to initialise mouse...");
exit();
}
count=sizeof(menu)/sizeof(char *);
settextstyle(TRIPLEX_FONT,0,3);
displaymenu(menu,count,100,100);
for(i=0;i<count;i++)
{
if(textwidth(menu[i])>width)
width=textwidth(menu[i]);
}
buffer=malloc(sizeof(menu));
savemenu(menu,buffer,width,count,100,100);
while(choice!=4)
{
choice=getresponse(menu,buffer,width,count,100,100);
gotoxy(50,15);
printf("you selected%s",menu[choice-1]);
}
displaymenu(char**menu,int count,int x1,int y1)
{
int i,h;
h=textheight(menu[0]);
for(i=0;i<count;i++)
{
outtexttxy(x1,y1+i*(h+5),menu[i]);
}
}
savemenu(char**menu,char**buffer,int width,int count,int x1,int y1)
{
int i,x2,yy1,yy2,area,h;
h=textheight(menu[0]);
for(i=0;i<count;i++)
{
x2=x1+width;
yy1=y1+i*(h+5);
yy2=y1+(i+1)*(h+5);
area=imagesize(x1,yy1,x2,yy2);
buffer[i]=malloc(area);
getimage(x1,yy1,x2,yy2,buffer[i]);
}
}
getresponse(char**menu,char**buffer,int width,int count,int x1,int y1)
{
int choice=1,prevchoice=0,x,y,x2,y2,button;
int in,i,h;
h=textheight(menu[0]);
y2=y1+count*(h+5);
x2=x1+width;
rectangle(x1-5,y1-5,x2+5,y2+5);
while(1)
{
getmousepos(&button,&x,&y);
if(x>=x1 &&x<=x2 && y>=y1 && y<=y2)
{
in=1;
for(i=1;i<=count;i++)
{
if(y<=y1+i*(h+5))
{
choice=i;
break;
}
}
if(prevchoice!=choice)
{
hidemouseptr();
highlight(buffer,choice,h,x1,y1);
if(prevchoice)
dehighlight(buffer,prevchoice,h,x1,y1);
prevchoice=choice;
showmouseptr();
}
if((button & 1)==1)
{
while((button & 1)==1)
getmousepos(&button,&x,&y);
if(x>=x1 && x<=x2 && y>=y1 && y<=y2)
return(choice);
}
}
else
{
if(in==1)
{
in=0;
prevchoice=0;
hidemouseptr();
dehighlight(buffer,choice,h,x1,y1);
showmouseptr();
}
}
}
}
highlight(char**menu,char**buffer,int width,int count,int x1,int y1)
{
putimage(x1,y1+(ch-1)*(h+5),buffer[ch-1],NOT_PUT);
}
dehighlight(char**menu,char**buffer,int width,int count,int x1,int y1)
{
putimage(x1,y1+(ch-1)*(h+5),buffer[ch-1],COPY_PUT);
}
initmouse()
{
i.x.ax=0;
int86(0x33,&i,&o);
return(o.x.ax);
}
showmouseptr()
{
i.x.ax=1;
int86(0x33,&i,&o);
}
hidemouseptr()
{
i.x.ax=2;
int86(0x33,&i,&o);
}
getmousepos(int*button,int*x,int*y)
{
i.x.ax=3;
int86(0x33,&i,&o);
*button=o.x.bx;
*x=o.x.cx;
*y=o.x.dx;
}
}
}
Friday, 4 May 2012
Posted by ANIMESH SHAW
Cricket Record Keeping Project in C++
//CRICKET RECORD KEEPING
//By Aditya K R (adityakr6124@gmail.com)
//Downloaded From c4cpp.co.nr
#include<fstream.h>
#include<conio.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h>
#include<process.h>
#include<iostream>
using namespace std;
class data
{char name[30];
int playercode;
int M1R;
int M2R;
int M3R;
int total_run;
public:
data()
{playercode=0;
strcpy(name,"");
M1R=0;
M2R=0;
M3R=0;
total_run=0;
}
void enter_name_runs() //TO TAKE ENTRY OF NEW RECORDS
{cout<<"\nEnter player code(Integral) : ";
cin>>playercode;
cout<<"\nEnter player name : ";
gets(name);
cout<<"\nFirst match run(s) : ";
cin>>M1R;
cout<<"\nSecond match run(s) : ";
cin>>M2R;
cout<<"\nThird match run(s) : ";
cin>>M3R;
total_runs();
}
void show_record() //TO DISPLAY THE RECORDS EXISTING IN THE FILE
{cout<<"\nPlayer code :"<<playercode;
cout<<"\nPlayer name : "<<name;
cout<<"\nFirst match run(s) : "<<M1R;
cout<<"\nSecond match run(s) : "<<M2R;
cout<<"\nThird match run(s) : "<<M3R;
cout<<"\nTotal run(s) : "<<total_run;
}
void total_runs() //CALCULATE TOTAL RUNS
{total_run=M1R+M2R+M3R;
}
int getplayercode()
{return playercode;
}
int gettotalruns()
{return total_run;
}
char* get_name()
{return name;
}
void modify_data() //TAKE DATA TO MODIFIFY EXISTING RECORD
{cout<<"\nEnter new data for modification :::::::: ";
cout<<"\nEnter First match run(s) : ";
cin>>M1R;
cout<<"\nEnter Second match run(s) : ";
cin>>M2R;
cout<<"\nEnter Third match run(s) : ";
cin>>M3R;
total_runs();
} };
data d;
fstream file;
fstream file1;
//* * * * * * * * * * CALCULATE HIGHEST RUN(s) * * * * * * * * * * * * * * * *
void highest()
{ file.open("record.dat",ios::in|ios::binary);
int post=0,tr=0,plr_code=0,run=0;
file.read((char*)&d,sizeof(d));
while(file)
{run=d.gettotalruns();
if(run>tr)
{post=file.tellg();
tr=run;
}
file.read((char*)&d,sizeof(d));
}file.close();
file.open("record.dat",ios::in|ios::binary);
file.seekg(post-sizeof(d));
file.read((char*)&d,sizeof(d));
cout<<"\n::::::::::Highest run getter data::::::::::";
cout<<"\nHighest run(s) getter code : "<<d.getplayercode();
cout<<"\nHighest run getter player is : "<<d.get_name();
cout<<"\nPlayer total run(s) are : "<<tr;
float avg;
avg=(tr)/3;
cout<<"\n Player average is : "<<avg;
file.close();
}
//* * * * * * * * * * * * INSERT NEW RECORD(s) * * * * * * * * * * * * * * * *
void insert()
{int i,no;
file.open("record.dat",ios::in|ios::app|ios::binary);
cout<<"\n ::Entry of new record(s):: ";
cout<<"\nHow many record(s) you want to enter : ";
cin>>no;
for(i=1;i<=no;i++)
{d.enter_name_runs(); //insert records
file.write((char*)&d,sizeof(d));
}file.close();
}
//* * * * * * * * * * * * * DISPLAY EXISTING RECORD(s) * * * * * * * * * * * * * *
void display()
{file.open("record.dat",ios::in|ios::binary);
cout<<"\n|||||||||||||||||||||| Entered record(s) ||||||||||||||||||||||||";
file.read((char*)&d,sizeof(d));
while(file)
{d.show_record();
file.read((char*)&d,sizeof(d));
}file.close();
}
//* * * * * * * * * * * * * SEARCH RECORD * * * * * * * * * * * * * * * *
void search()
{int p,r,srch=0;
file.open("record.dat",ios::in|ios::binary);
cout<<"\nEnter the player code to see his records : ";
cin>>r;
file.seekg(0);
file.read((char*)&d,sizeof(d));
while(file)
{p=d.getplayercode();
if(r==p)
{d.show_record();
srch=1;
break;
}
else
{ file.read((char*)&d,sizeof(d));
}
}file.close();
if(srch==0)
{cout<<"\nThere is no record which have this playercode .";
}
}
//* * * * * * * * * * * * * * MODIFY DATA * * * * * * * * * * * * * * * * * *
void modify()
{int posi=0,got=0,dmd=0;
cout<<"\nEnter the playercode whose record to be modified : ";
cin>>dmd;
int ifdata=1;
file.open("record.dat",ios::in|ios::out|ios::binary);
posi=file.tellg();
while(file)
{ file.read((char*)&d,sizeof(d));
got=d.getplayercode();
if(dmd==got)
{file.seekg(posi);
d.modify_data();
ifdata=2;
file.write((char*)&d,sizeof(d));
break;
}
posi=file.tellg();
}
file.close();
if(ifdata==1)
{cout<<"\n Data not available for modification ";
}
}
//* * * * * * * * * * * * * * * DELETE RECORD* * * * * * * * * * * * * * * * * * *
void delete_record()
{int pointer=0,remove_record=0,size=0,code_get=0;
// size=sizeof(file);
cout<<"\n Enter the player code whose record to be deleated : ";
cin>>remove_record;
file.open("record.dat",ios::in|ios::out|ios::binary);
file1.open("tempo.dat",ios::in|ios::out|ios::binary);
file.seekg(0);
while(file)
{file.read((char*)&d,sizeof(d));
code_get=d.getplayercode();
if(remove_record==code_get)
{cout<<" ";
}
else
{ file1.write((char*)&d,sizeof(d));
}
}file.close();
file1.close();
remove("record.dat");
rename("tempo.dat","record.dat");
}
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
void main()
{clrscr();
int choice;
char ans='n';
do
{cout<<"\n=*=*=*=*=*=*=*=*=* PLAYER RECORD KEEPING SYSTEM -Animesh*=*=*=*=*=*=*=*=*=*";
cout<<"\n 1.INSERT RECORD \n 2.DISPLAY RCEORD \n 3.SEARCH RECORD \n 4.MODIFY RECORD \n 5.HIGHEST RUNS \n 6.DELETE PREVIOUS ENTERED RECORD \n 7.EXIT ";
cout<<"\n Enter any one of the options : ";
cin>>choice;
switch(choice)
{case 1: insert();
break;
case 2: display();
break;
case 3: search();
break;
case 4: modify();
break;
case 5: highest();
break;
case 6: delete_record();
break;
case 7: exit(0);
break;
default: cout<<"\n Enter choice between 1 to 6 ";
}
cout<<"\n Do you want to choose any other option ? :(y/n): ";
cin>>ans;
clrscr();
}while(ans=='y'||ans=='Y');
getch();
}
Search An Element in Linked List in C
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node*next;
};
void insert(struct node**p,int num) /*Function for inserting an
element into a list */
{
if(*p==NULL)
{
(*p)=(struct node*)malloc(sizeof(struct node));
(*p)->next=NULL;
(*p)->data=num;
}
else
{
insert(&((*p)->next),num);
}
}
void display(struct node*p) /*Function for displaying the list*/
{
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
void reverse(struct node**p) /*Function for reversing the list by
recursion */
{
struct node*q,*r,*x;
int d;
q=(*p); /*stores the address of the first element */
x=q; /*also stores the element of the first element for
counter pourpose */
d=q->data; /*stores the data of the first element*/
r=q->next; /*stores the address of the second element in the list
*/
free(q); /*deletes the first element of the list*/
if(x==NULL)
return ;
else
{
reverse(&(r));/*Recursive call*/
insert(p,d); /*This function is put in the stack so the first
will be taken as last element for the new list */
}
}
void main()
{
clrscr();
struct node*p=NULL;
int n,d,i=0;
printf("How many...?");
scanf("%d",&n);
while(i++!=n)
{
scanf("%d",&d);
insert(&p,d);
}
display(p);
reverse(&p);
printf("The reversed list is...");
display(p);
getch();
}
Wednesday, 2 May 2012
Posted by ANIMESH SHAW
Heapsort algorithm Program in C
#include <stdlib.h>
#include <stdio.h>
#define uint unsigned int
typedef int (*compare_func)(int, int);
void heap_sort(int This[], compare_func func_pointer, uint len)
{
/* heap sort */
uint half;
uint parents;
if (len <= 1)
return;
half = len >> 1;
for (parents = half; parents >= 1; --parents)
{
int tmp;
int level = 0;
uint child;
child = parents;
/* bottom-up downheap */
/* leaf-search for largest child path */
while (child <= half)
{
++level;
child += child;
if ((child < len) &&
((*func_pointer)(This[child], This[child - 1]) > 0))
++child;
}
/* bottom-up-search for rotation point */
tmp = This[parents - 1];
for (;;)
{
if (parents == child)
break;
if ((*func_pointer)(tmp, This[child - 1]) <= 0)
break;
child >>= 1;
--level;
}
/* rotate nodes from parents to rotation point */
for (;level > 0; --level)
{
This[(child >> level) - 1] =
This[(child >> (level - 1)) - 1];
}
This[child - 1] = tmp;
}
--len;
do
{
int tmp;
int level = 0;
uint child;
/* move max element to back of array */
tmp = This[len];
This[len] = This[0];
This[0] = tmp;
child = parents = 1;
half = len >> 1;
/* bottom-up downheap */
/* leaf-search for largest child path */
while (child <= half)
{
++level;
child += child;
if ((child < len) &&
((*func_pointer)(This[child], This[child - 1]) > 0))
++child;
}
/* bottom-up-search for rotation point */
for (;;)
{
if (parents == child)
break;
if ((*func_pointer)(tmp, This[child - 1]) <= 0)
break;
child >>= 1;
--level;
}
/* rotate nodes from parents to rotation point */
for (;level > 0; --level)
{
This[(child >> level) - 1] =
This[(child >> (level - 1)) - 1];
}
This[child - 1] = tmp;
} while (--len >= 1);
}
#define ARRAY_SIZE 250000
int my_array[ARRAY_SIZE];
void init()
{
int indx;
for (indx=0; indx < ARRAY_SIZE; ++indx)
{
my_array[indx] = rand();
}
}
int cmpfun(int a, int b)
{
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}
int main()
{
int indx;
init();
heap_sort(my_array, cmpfun, ARRAY_SIZE);
for (indx=1; indx < ARRAY_SIZE; ++indx)
{
if (my_array[indx - 1] > my_array[indx])
{
printf("bad sort\n");
return(1);
}
}
return(0);
}
Prgram to insert & delete the elemnts from queue
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class queue
{
private:
int i,r,q[25],front,rear;
public:
void enqueue(int);
void dequeue();
void getdata();
};
void queue::getdata()
{
clrscr();
cout<<endl<<"enter the="" range="" of="" queue:";="" <br=""> cin>>r;
cout<<endl<<"enter the="" elments="" of="" queue:";="" <br=""> for(i=0;i<r;i++) <br=""> {
cin>>q[i];
}
front=q[0];
rear=q[2];
}
void queue::dequeue()
{
int item;
if(front==0)
{
cout<<endl<<"queue is="" empty.";="" <br=""> exit(0);
}
else
{
item=q[1];
}
if(front==rear)
{
front=0;
rear=0;
}
else
{
front=front+1;
}
cout<<endl<<"after delection;";="" <br="">
for(i=0;i<r;i++) <br=""> {
cout<<"\t"<<q[i]; <br=""> }
}
void queue::enqueue(int item)
{
if(rear==r)
{
cout<<endl<<"queue is="" full.";="" <br=""> exit(0);
}
else
{
if(rear==0 && front==0)
{
front=1;
rear=1;
}
r=r+1;
q[r]=item;
}
cout<<endl<<"after insertion.";="" <br=""> for(i=0;i<r+1;i++) <br=""> {
cout<<"\t"<<q[i]; <br=""> }
}
void main()
{
int ch,no;
clrscr();
char cho;
queue q;
q.getdata();
cout<<endl<<endl<<"select the="" operation="" you="" ";="" <br=""> cout<<"want to perform on queue:";
cout<<endl<<endl<<"1) insert"<<endl<<endl<<"2)="" delete";="" <br=""> cout<<endl<<endl<<"enter your="" choice:";="" <br=""> cin>>ch;
do
{
switch(ch)
{
case 1:
cout<<endl<<"enter the="" number="" which="" you="" want="" to="" insert:";="" <br=""> cin>>no;
q.enqueue(no);
break;
case 2:
q.dequeue();
break;
}
cout<<endl<<endl<<"do you="" want="" to="" continue:";="" <br=""> cin>>cho;
}
while(cho=='y'||cho=='Y');
}
Program to generate cos series in C
# include <stdio.h>
# include <conio.h>
main()
{
int i,p,n;
clrscr();
printf("enter the number in term of series");
scanf("%d",&n);
printf("xcos(x)=1");
for(i=1;i<=n;i++)
{
p=2*i;
if(i%2==0)
printf("+");
else
printf("-");
printf(x^%d/%d!",p,p);
getch();
}
}
Program to find the reminder without using reminder in C
#include <stdio.h>
#include <conio.h>
main()
{
int a,b;
clrscr();
printf("enter the value of a=");
scanf("%d",&a);
printf("enter the value of b=");
scanf("%d",&b);
while(a-b>=b)
{
a=a-b;
}
printf("the reminder is =%d",a-b);
getch();
}
Write a program to find permutation in c
#include<stdio.h>
#include<stdlib.h>
int lev=-1,n,val[50],a[50];
void main()
{
int i,j;
clrscr();
printf("Enter how many numbers");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
val[i]=0;
j=i+1;
scanf("%d",&a[j]);
}
visit(0);
getch();
}
visit(int k)
{
int i;
val[k]=++lev;
if(lev==n)
{
for(i=0;i<=n;i++)
printf("%2d",a[val[i]]);
printf(" ");
}
for(i=0;i<=n;i++)
if(val[i]==0)
visit(i);
lev--;
val[k]=0;
}
Program to Count Blanks Spaces ,Tabs and Newlines in Given String In C
#include<stdio.h>
int main(void)
{
int nb,nt,nl,c;
nb=nt=nl=0;
while((c=getchar())!=EOF)
{
if(c==' ')
++nb;
if(c==' ')
++nt;
if(c==' ')
++nl;
}
printf("No. of Blanks is %d,No. of Tabs is %d and No. of Newlines is %d",nb,nt,nl);
return 0;
}
CPU scheduling (Round Robin) Program in C
#include<stdio.h>
#include<conio.h>
main()
{
int st[10],bt[10],wt[10],tat[10],n,tq;
int i,count=0,swt=0,stat=0,temp,sq=0;
float awt=0.0,atat=0.0;
clrscr();
printf("Enter number of processes:");
scanf("%d",&n);
printf("Enter burst time for sequences:");
for(i=0;i<=n;i++)
{
scanf("%d",&bt[i]);
st[i]=bt[i];
}
printf("Enter time quantum:");
scanf("%d",&tq);
while(1)
{
for(i=0,count=0;i<=n;i++)
{
temp=tq;
if(st[i]==0)
{
count++;
continue;
}
if(st[i]=>tq)
st[i]=st[i]-tq;
else
if(st[i]>=0)
{
temp=st[i];
st[i]=0;
}
sq=sq+temp;
tat[i]=sq;
}
if(n==count)
break;
}
for(i=0;i<=n;i++)
{
wt[i]=tat[i]-bt[i];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("Process_no Burst time Wait time Turn around time
");
for(i=0;i<=n;i++)
printf("%d %d %d %d
",i+1,bt[i],wt[i],tat[i]);
printf("Avg wait time is %f
Avg turn around time is %f",awt,atat);
getch();
}
Posted by ANIMESH SHAW
Program to Frind the biggest and smallest number from given array set
main()
{
int array[]={5,66,76,34,23,51,94,18,35};
int i,count,large=1,small=32767,n;
clrscr();
for(count=0;count<=9;count++)
{
printf("\n %d-------> %d",count,array[count]);
}
for(count=0;count<=9;count++)
{
if(large < array[count])
{
large = array[count];
}
if(small >= array[count])
{
small=array[count];
}
}
printf("\n largest no in the array is %d",large);
printf("\n smallest no in the array is %d",small);
getch();
}
Program to create rectangle
#include<graphics.h>
main()
{
int driver,mode,i=10;
driver=0;
mode=VGAHI;
initgraph(&driver,&mode,"\\tc\\bgi");
for(i=10;i<=100;i+10)
{
rectangle(254,236,456,368);
clearviewpart();
delay(500);
moveto(i,i);
}
getch();
restorecrtmode();
closegraph();
}
Program to swap the numbers by Call By Referance in C
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a=10,b=20;
void swapr(int*,int*);
clrscr();
printf("\nEnter The Vale Of A & B:=");
scanf("%d%d",&a,&b);
printf("\n\t A=%d",a);
printf("\n\t B=%d",b);
swapr(a,b);
printf("\n\n\tAfter Sweping The Value");
printf("\n\n\t A=%d",a);
printf("\n\t B=%d",b);
getch();
}
void swapr(int,int)
int *x,*y;
{
int *z=0;
*z=*x;
*x=*y;
*y=*z;
}
C Program to print number of days in given Month
view plainprint?
#include<stdio.h>
#include<conio.h>
main()
{
int mon;
printf("Enter number ( 1 - 12 ): ");
scanf("%d",&mon);
switch(mon)
{
case 1:
printf("January has 31 days");
break;
case 2:
printf("February has 28 days");
break;
case 3:
printf("March has 31 days");
break;
case 4:
printf("April has 30 days");
break;
case 5:
printf("May has 31 days");
break;
case 6:
printf("June has 30 days");
break;
case 7:
printf("July has 31 days");
break;
case 8:
printf("August has 31 days");
break;
case 9:
printf("September has 30 days");
break;
case 10:
printf("October has 31 days");
break;
case 11:
printf("November has 30 days");
break;
case 12:
printf("December has 31 days");
break;
default:
printf("INVALID INPUT! ");
}
getch();
}
Converting Degree to Radian
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
float a, b, c, d;
char s;
printf("Enter Degrees: ");
scanf("%f", &a);
printf("Enter Minutes: ");
scanf("%f", &b);
c=((b/60)+a)*(3.1416/180);
printf("\nThe radians is %.0f", c);
printf("\n\nPress y to continue and x to exit: ");
scanf("%s", &s);
if(s=='y') {
system("cls");
return main();
getch();
}
if(s=='x')
{
return 0;
}}
Header Files
A header file is a file containing C declarations and macro definitions (see section 3. Macros) to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive `#include'.
Header files serve two purposes.
- System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.
- Your own header files contain declarations for interfaces between the source files of your program. Each time you have a group of related declarations and macro definitions all or most of which are needed in several different source files, it is a good idea to create a header file for them.
Including a header file produces the same results as copying the header file into each source file that needs it. Such copying would be time-consuming and error-prone. With a header file, the related declarations appear in only one place. If they need to be changed, they can be changed in one place, and programs that include the header file will automatically use the new version when next recompiled. The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'. It is most portable to use only letters, digits, dashes, and underscores in header file names, and at most one dot.
2.1 Include Syntax 2.2 Include Operation 2.3 Search Path 2.4 Once-Only Headers 2.5 Computed Includes 2.6 Wrapper Headers 2.7 System Headers
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.1 Include Syntax
Both user and system header files are included using the preprocessing directive `#include'. It has two variants:
#include <file>- This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the `-I' option (see section 12. Invocation).
#include "file"- This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the same directories used for
<file>.
The argument of `#include', whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus,
#include <x/*y> specifies inclusion of a system header file named `x/*y'.
However, if backslashes occur within file, they are considered ordinary text characters, not escape characters. None of the character escape sequences appropriate to string constants in C are processed. Thus,
#include "x\n\\y" specifies a filename containing three backslashes. (Some systems interpret `\' as a pathname separator. All of these also interpret `/' the same way. It is most portable to use only `/'.)
It is an error if there is anything (other than comments) on the line after the file name.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.2 Include Operation
The `#include' directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current file. The output from the preprocessor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the `#include' directive. For example, if you have a header file `header.h' as follows,
char *test (void); |
and a main program called `program.c' that uses the header file, like this,
int x;
#include "header.h"
int
main (void)
{
puts (test ());
}
|
the compiler will see the same token stream as it would if `program.c' read
int x;
char *test (void);
int
main (void)
{
puts (test ());
}
|
Included files are not limited to declarations and macro definitions; those are merely the typical uses. Any fragment of a C program can be included from another file. The include file could even contain the beginning of a statement that is concluded in the containing file, or the end of a statement that was started in the including file. However, a comment or a string or character constant may not start in the included file and finish in the including file. An unterminated comment, string constant or character constant in an included file is considered to end (with an error message) at the end of the file.
To avoid confusion, it is best if header files contain only complete syntactic units--function declarations or definitions, type declarations, etc.
The line following the `#include' directive is always treated as a separate line by the C preprocessor, even if the included file lacks a final newline.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.3 Search Path
GCC looks in several different places for headers. On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with
#include <file> in:/usr/local/include /usr/lib/gcc-lib/target/version/include /usr/target/include /usr/include |
For C++ programs, it will also look in `/usr/include/g++-v3', first. In the above, target is the canonical name of the system GCC was configured to compile code for; often but not always the same as the canonical name of the system it runs on. version is the version of GCC in use.
You can add to this list with the `-Idir' command line option. All the directories named by `-I' are searched, in left-to-right order, before the default directories. You can also prevent GCC from searching any of the default directories with the `-nostdinc' option. This is useful when you are compiling an operating system kernel or some other program that does not use the standard C library facilities, or the standard C library itself.
GCC looks for headers requested with
#include "file" first in the directory containing the current file, then in the same places it would have looked for a header requested with angle brackets. For example, if `/usr/include/sys/stat.h' contains #include "types.h", GCC looks for `types.h' first in`/usr/include/sys', then in its usual search path.
`#line' (see section 6. Line Control) does not change GCC's idea of the directory containing the current file.
You may put `-I-' at any point in your list of `-I' options. This has two effects. First, directories appearing before the `-I-' in the list are searched only for headers requested with quote marks. Directories after `-I-' are searched for all headers. Second, the directory containing the current file is not searched for anything, unless it happens to be one of the directories named by an `-I' switch.
`-I. -I-' is not the same as no `-I' options at all, and does not cause the same behavior for `<>' includes that `""' includes get with no special options. `-I.'searches the compiler's current working directory for header files. That may or may not be the same as the directory containing the current file.
If you need to look for headers in a directory named `-', write `-I./-'.
There are several more ways to adjust the header search path. They are generally less useful. See section 12. Invocation.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.4 Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time.
The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this:
/* File foo. */ #ifndef FILE_FOO_SEEN #define FILE_FOO_SEEN the entire file #endif /* !FILE_FOO_SEEN */ |
This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because
FILE_FOO_SEEN is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice.
GNU CPP optimizes even further. It remembers when a header file has a wrapper `#ifndef'. If a subsequent `#include' specifies that header, and the macro in the `#ifndef' is still defined, it does not bother to rescan the file at all.
You can put comments outside the wrapper. They will not interfere with this optimization.
The macro
FILE_FOO_SEEN is called the controlling macro or guard macro. In a user header file, the macro name should not begin with `_'. In a system header file, it should begin with `__' to avoid conflicts with user programs. In any kind of header file, the macro name should contain the name of the file and some additional text, to avoid conflicts with other header files.| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.5 Computed Includes
Sometimes it is necessary to select one of several different header files to be included into your program. They might specify configuration parameters to be used on different sorts of operating systems, for instance. You could do this with a series of conditionals,
#if SYSTEM_1 # include "system_1.h" #elif SYSTEM_2 # include "system_2.h" #elif SYSTEM_3 ... #endif |
That rapidly becomes tedious. Instead, the preprocessor offers the ability to use a macro for the header name. This is called a computed include. Instead of writing a header name as the direct argument of `#include', you simply put a macro name there instead:
#define SYSTEM_H "system_1.h" ... #include SYSTEM_H |
SYSTEM_H will be expanded, and the preprocessor will look for `system_1.h' as if the `#include' had been written that way originally. SYSTEM_H could be defined by your Makefile with a `-D' option.
You must be careful when you define the macro. `#define' saves tokens, not text. The preprocessor has no way of knowing that the macro will be used as the argument of `#include', so it generates ordinary tokens, not a header name. This is unlikely to cause problems if you use double-quote includes, which are close enough to string constants. If you use angle brackets, however, you may have trouble.
The syntax of a computed include is actually a bit more general than the above. If the first non-whitespace character after `#include' is not `"' or `<', then the entire line is macro-expanded like running text would be.
If the line expands to a single string constant, the contents of that string constant are the file to be included. CPP does not re-examine the string for embedded quotes, but neither does it process backslash escapes in the string. Therefore
#define HEADER "a\"b" #include HEADER |
looks for a file named `a\"b'. CPP searches for the file according to the rules for double-quoted includes.
If the line expands to a token stream beginning with a `<' token and including a `>' token, then the tokens between the `<' and the first `>' are combined to form the filename to be included. Any whitespace between tokens is reduced to a single space; then any space after the initial `<' is retained, but a trailing space before the closing `>' is ignored. CPP searches for the file according to the rules for angle-bracket includes.
In either case, if there are any tokens on the line after the file name, an error occurs and the directive is not processed. It is also an error if the result of expansion does not match either of the two expected forms.
These rules are implementation-defined behavior according to the C standard. To minimize the risk of different compilers interpreting your computed includes differently, we recommend you use only a single object-like macro which expands to a string constant. This will also minimize confusion for people reading your program.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.6 Wrapper Headers
Sometimes it is necessary to adjust the contents of a system-provided header file without editing it directly. GCC's
fixincludes operation does this, for example. One way to do that would be to create a new header file with the same name and insert it in the search path before the original header. That works fine as long as you're willing to replace the old header entirely. But what if you want to refer to the old header from the new one?
You cannot simply include the old header with `#include'. That will start from the beginning, and find your new header again. If your header is not protected from multiple inclusion (see section 2.4 Once-Only Headers), it will recurse infinitely and cause a fatal error.
You could include the old header with an absolute pathname:
#include "/usr/include/old-header.h" |
There is no way to solve this problem within the C standard, but you can use the GNU extension `#include_next'. It means, "Include the next file with this name." This directive works like `#include' except in searching for the specified file: it starts searching the list of header file directories after the directory in which the current file was found.
Suppose you specify `-I /usr/local/include', and the list of directories to search also includes `/usr/include'; and suppose both directories contain`signal.h'. Ordinary
#include <signal.h> finds the file under `/usr/local/include'. If that file contains #include_next <signal.h>, it starts searching after that directory, and finds the file in `/usr/include'.
`#include_next' does not distinguish between
<file> and "file" inclusion, nor does it check that the file you specify has the same name as the current file. It simply looks for the file named, starting with the directory in the search path after the one where the current file was found.
The use of `#include_next' can lead to great confusion. We recommend it be used only when there is no other alternative. In particular, it should not be used in the headers belonging to a specific program; it should be used only to make global corrections along the lines of
fixincludes.| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.7 System Headers
The header files declaring interfaces to the operating system and runtime libraries often cannot be written in strictly conforming C. Therefore, GCC gives code found in system headers special treatment. All warnings, other than those generated by `#warning' (see section 5. Diagnostics), are suppressed while GCC is processing a system header. Macros defined in a system header are immune to a few warnings wherever they are expanded. This immunity is granted on an ad-hoc basis, when we find that a warning generates lots of false positives because of code in macros defined in system headers.
Normally, only the headers found in specific directories are considered system headers. These directories are determined when GCC is compiled. There are, however, two ways to make normal headers into system headers.
The `-isystem' command line option adds its argument to the list of directories to search for headers, just like `-I'. Any headers found in that directory will be considered system headers.
All directories named by `-isystem' are searched after all directories named by `-I', no matter what their order was on the command line. If the same directory is named by both `-I' and `-isystem', `-I' wins; it is as if the `-isystem' option had never been specified at all.
There is also a directive,
#pragma GCC system_header, which tells GCC to consider the rest of the current include file a system header, no matter where it was found. Code that comes before the `#pragma' in the file will not be affected. #pragma GCC system_header has no effect in the primary source file.
On very old systems, some of the pre-defined system header directories get even more special treatment. GNU C++ considers code in headers found in those directories to be surrounded by an
extern "C" block. There is no way to request this behavior with a `#pragma', or from the command line.Posted by ANIMESH SHAW
Posted by ANIMESH SHAW
