Benefits of splitting interface and implementation in C++
I'm using C++ and I'm considering putting my function implementation into .h. I know that .h file is for definitions and .cpp is for implementations but how s开发者_开发知识库plitting all files into headers and sources will benefit me. Well if my aim would be to create static or dynamic library than of course that would make a difference but I am creating this code for myself and not planning to make a library out of it. So is there any other benefit from splitting source from definition?
The obvious goal is to reduce coupling : as soon as you change a header file, anything that includes it must be recompiled. This can rapidly have a strong impact on compilation times (even in a small project).
You can put almost all code into .h file, it will be header-only library. But if you want more faster partial recompilation, or if you want put some code to shared library - you should create .cpp files.
Depending on the size of your project it will save you compile time and make it possible to know all ressources etc. (unless you put everything into one single file).
The better your header files are organized the less work your compiler has to do to apply changes. Also looking in a small header file to look up some forgotten parameter information is a lot easier than scrolling through a hole cpp file.
One other obvious improvement is in avoiding re-compiling the code for your function in each file that uses it, instead compiling it once and using it where needed.
Another is that it follows convention (and the standard's one definition rule), so others will find it much easier to deal with and understand.
It depends on the size of the project. Up to about 500 LOC, I tend to put everything in a single file, with the function definitions in the class. Except that up to about 500 LOC, I generally use a simpler language than C++; something like AWK.
As soon as the code gets big enough to warrent several source files, it's definitely an advantage to put as little as possible in the header, and that means putting all of the function definitions in the source files. And as soon as the classes become non-trivial, you probably don't want the function definitions in the class itself, for readability reasons.
-- James Kanze
精彩评论