Thursday, June 16, 2005

How to make and access your own “.h” file in C++

As a programmer, there are times wherein you will have to use a template. Templates are usually used whenever you have projects that have some common segments within it. Others would just copy and paste some of these lines to the other programs. But there is a quicker way on how to minimize your time at work. This can be done through user-defined files.

In C++, you can make your own files “.h” like the standard files in #include directive. This article presents how to make and access your own “.h” file.

How to make the user-defined file

#include “iostream.h”
#include “conio.h”

void clr(void)
{
clrscr();
cout<<”This is an example of a program using a user-defined file\n”;
}

Then save this program as “sample.h”. Do not run this program has an error. The error in this program is not significant and you do not have to worry about. As you notice there is no main function. That’s the cause of error. If there is another cause of error then you have to fix it.

Make a program and link the file.

#include “iostream.h”
#include “conio.h”
#include “sample.h”

main()
{
clr();
cout<<”Hello World”;
getch();
return 0;
}

Run the above program.

Let’s take a look at the program

There are 3 links in there. You noticed I also used quotations instead of the angle bracket. C++ gives that option.

Clr() is not a built-in function in C++ but since you have defined it in your sample.h file, there is nothing to worry about. What C++ will during compilation is that it will look for the definition of clr() in sample.h file when it can not locate it in conio.h and iostream.h

User-defined files can make your program more personalized. What I mean is that you can use your name or any words as a function name like in clr. I can replace the clr in the file and in the program to Gomez and run the program!

0 Comments:

Post a Comment

<< Home