Thursday, July 30, 2009

How do i use a header file in a c++ program?

I have constantly tried to use classes in my c++ programs in header files but they never work, i always either get a error that says the included file doesn't exist or the program runs then just closes unexpectedly when it tries to use the header file.

How do i use a header file in a c++ program?
First if your putting classes into header files, make sure those header files are saved as .hpp files not .h files.





Second make sure you either are including your headers in only one place or they have preprocessor commands to stop multiple copies from being created (using #define, #ifndef and #endif)





P.S.


Even if the header file is included in the project, you can't just use the name with #include unless the header is in the same directory.





Also try putting your classes into your cpp files themselves and see if it's the classes and not putting them in headers that is causing your program to close. Also another major thing is if your program is a command line program, unless you have some kind of pause at the end (like a getch() or a system(PAUSE)), windows will by default close the window after the program finishes running.
Reply:If it is your own header file you have created, you need to use double quotes in the include statement. Heres an example:





#include "MyClass.h"





If you are storing your class in a subfolder of the program, such as 'Classes', you would use #include "Classes\MyClass.h"
Reply:If its compiling, then the problem isnt because of your header files





The proper way to include it would be


#include "myheader.h"





Note you use .h and not .hpp, though it doesnt really matter


You need to debug your program to see why its just quitting. It wil be something in the .c or .cpp that isnt working properly


No comments:

Post a Comment