1

I have seen in many libraries which contains two files one is .H file and another is a .CPP file. .h is a header file which contains function prototype and .CPP contains actual c++ code for every function in header file.

I want to ask that can I make a single .h file and write all c++ functions and class in it. And include that .h file when ever it is necessary in main.cpp

Ganesh S
  • 21
  • 1
  • 4

3 Answers3

6

Yes, you can. This is sometimes called header-only library.

Of course, since your functions may be included in several CPP files of the same program, you need to make them all inline (or with internal linkage, static or in an anonymous namespace).

You can see a few of these in the excelent boost library collection.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
1

I want to ask that can I make a single .h file and write all c++ functions and class in it. And include that .h file when ever it is necessary in main.cpp

Yes, you can do that. It's possible to put all the definitions inline into the header file.
Though that's unusual, unless you have a header only (template) library.

One of the reasons to separate the definitions out into a own translation unit is, that you don't have to recompile all the dependent code, when some small bits of the implementation are changed.

user0042
  • 7,917
  • 3
  • 24
  • 39
1

Yes You can do this. all the code in a header will be pasted into the "main.cpp" file at compile time. It's standard that declarations are in the header or hpp and then the implementation is done in the source or cpp. however you can just put it all in a header and include the header file which will work after its compiled. You can declare exactly whats in a header into your "main.cpp" then implement it into another cpp file and not use a .h file then compile it and it will work the same as #include "MyClass.hpp" (note I personally use hpp for c++ headers and h for c headers makes things easier for me.)

killer
  • 372
  • 1
  • 5
  • 15