简体   繁体   中英

Should I always split my files into declarations (.h) and definitions (.cpp)

To make some code easier to read I am splitting it across several files. One of those files just contains 2 initialisation methods. Is it worth creating a .h with the the declaration for those methods in, and including that, or should I just include the .cpp straight off, for just 2 methods, is it worth conforming to the standard?

You should never include cpp file, no matter how few definitions are in them: each definition included in several other cpp files would produce duplicate symbols, causing linking errors.

If you build a class that is used in multiple translation units (that's a fancy name for a cpp files) you should build a header for it. Templates go without a cpp file - only a header is necessary.

Although a common practice is to make one cpp/header pair for each class, it is OK to include multiple related classes in a single translation unit, and put all the declarations in a single header.

Like said before, you don't include .cpp files. If your code is needed around the project then headers are a must. However, you can always use extern too. http://www.cplusplus.com/forum/general/21368/

A .cpp file you include is a misnamed .h file.

.cpp and .h are extensions that mean something to programmers (and the occasional tool in the tool chain). If you start #include ing .cpp files, you'll confuse other programmers (including yourself in a few months/years), even if you convince your tool chain how to deal with it.

Creating a header-file only set of tools or functions is sometimes acceptable. Calling that file .cpp is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM