.h files. | Sololearn: Learn to code for FREE!


.h files.

I guess this isn't a solo learn question but it's c++, any recommendations on tutorial s for making header files


4/13/2017 9:13:50 PM

Adam Dewitt

4 Answers

New Answer


Here's an example, in your header you declare a class like this: (edit) forgot the #define HEADER_H under #pragma once #pragma once // add this at the top of your header so it can't be included more than once class MyClass { private: int somedata; public: MyClass(); void SomeMethod(); }; In your .cpp file you define your constructor and method: MyClass::MyClass() { } void MyClass::SomeMethod() { }


Header files contain your declarations, and source files contain your definitions. That's basically it. Notice that the header file contains header guards; this is so that you can include the header multiple times across different files without worrying about your declarations being include more than once. If you're using a modern compiler, you can also just use "#pragma once" at the top of the file. While non-standard, most compilers will support it. Here is an example of how you could use header/source files: In "Header.h": #ifndef HEADER_H #define HEADER_H class MyClass { public: int sum(int, int); } void freeFunction(); #endif In "Source.cc": #include "Header.h" #include <iostream> int MyClass::sum(int a, int b) { return a + b; } void freeFunction() { std::cout << "Hello, World!"; }


or if any one can give me an example of using one with the cpp I could figure it out from there


Use #ifndef + #define + #endif as the guy above suggested. #pragma once can lead to some problem related to naming.