FAQ About C++ Header Files
6. Your Questions Answered
Still have questions swirling around in your head? Let's tackle some frequently asked questions about C++ header files.
Q: What's the difference between `#include ` and `#include "iostream.h"`?
A: While you might see `"iostream.h"` in older C++ code, it's generally outdated. The correct way to include standard library headers in modern C++ is to use angle brackets (``). Also, avoid adding the `.h` suffix to standard headers in new code. This also applies to `string`, `vector` and any other common header files.
Q: Can I create my own header files?
A: Absolutely! Creating your own header files is a great way to organize your code and make it more reusable. Simply create a new file with a `.h` or `.hpp` extension and put your declarations in it. Remember to use `#ifndef`, `#define`, and `#endif` to prevent multiple inclusions (more on that later!).
Q: What is "include guard" and why is it so important?
A: Imagine including the same header file multiple times in a single program. Bad things happen! The compiler gets confused and starts throwing errors. Include guards are a way to prevent this from happening. They're a set of preprocessor directives that ensure that a header file is only included once. They look like this:
#ifndef MY_HEADER_H
#define MY_HEADER_H
// Header file contents go here
#endif
The `#ifndef` checks if the symbol `MY_HEADER_H` is already defined. If it's not, the `#define` defines it, and the header file contents are included. If it is already defined, the entire block is skipped, preventing multiple inclusions. Think of it as a gatekeeper for your header files.