Is it bad to put all ones code in an hpp and not even use a cpp file?

I was taught that one should use an hpp for function prototypes but the actual body of functions and structs should reside in a cpp. Helping a group with some code and have tried to find a good reference as to the compilation impacts by only using an hpp file!

Thanks in advance!
It's not a hard-written rule, but yes, generally, you want the declarations of the functions in the header file, and their implementations (definitions) in a corresponding .cpp file.

You can get away with making header-only implementations by use of templates/inline functions.

The struct itself needs to be defined in the header file if you want other people to be able to use it.
Last edited on
About declarations, definitions, and compilation ... see http://www.cplusplus.com/articles/yAqpX9L8/

However, the C++20 will introduce modules. See https://docs.microsoft.com/en-us/cpp/cpp/modules-cpp?view=vs-2019
yes, it is bad. the reverse is also bad, to put it all in cpp files and #include *those*.
these things both work for tiny, one coder projects with only a couple of files, but in larger projects you start getting all sorts of problems and stuff simply will not compile this way once it reaches a certain level of complexity in longer include chains.

Not only do you 'get away' with it for templates but templates are a special snowflake that require being done this way for technical reasons.

There are several problems putting all your function bodies into a header file.

1) For free functions, you have to deal with the same function being defined over and over again, in every translation unit that includes the header. This causes linker errors. Yes, you can do stuff to remove those errors, but why jump through those hoops in the first place? To what end?

2) Compile time:

a) You're having to compile every line of those header files for every source file. If you put all your fumction/method definitions into the header file, then you're recompiling them again and again, for every source file that includes it.

b) Recompiling: compilers figure out what they need to recompile when you change your code, and only recompile those translation units that need it. When you modify a line of your funtion definition, if it's in a source file, then the compiler will only recompile that source file. If it's in a header file, then it will recompile every source file that includes it.

3) Readability. When a user looks at a header file, they're generally interested in only seeing the things they need to know to use it - that is, the definition of the interface. Stuffing the header file full of implementation detail makes them harder for users to read.

4) What do you gain from putting everything in a header? What problem do you believe you have, that you believe will be solved by putting all your implemention detail into headers?
Topic archived. No new replies allowed.