When to put a C ++ function in a header file

I look at Boost and other C ++ libraries. The vast majority of Boost are implemented in header files.

My question is: under what conditions do you only implement the header (e.g. Boost) or also include the .cpp file?

+7
c ++ c boost header-files header
source share
2 answers

If you want to use the template in a different translation unit (i.e. a different source file), you should (almost always) define it in the header file. (There are exceptions, as are the comments below, but IMHO is a good rule of thumb.)

The same applies if you want to use the built-in function from another translation unit.

Otherwise, you should put the implementation in a separate .cpp file to minimize dependencies.

+7
source share

Understanding this problem mainly relates to understanding how C ++ compilers work. Things in the header files are mostly inserted into the source code of an entire group of compilation units using the #include statements. Each compilation unit is compiled into an object file, the object files are linked, and you get conflicts due to the fact that this material is replicated everywhere.

Exceptions are things that (at least historically) do not fall into the object file because the compiler directly processes them (for example, built-in functions) and things that cannot be compiled in one block and then linked to another because they are not fully defined (patterns). Template functions often get identically created in several compilation units, and the linker has special skills to discard duplicates.

This means that separating the interface and implementation into header and body files is not so clean. Ada has a much cleaner separation, but a more complex build process to compensate for IIRC. Java simply deleted individual files for the interface and implementation.

For many years, linkers were much more complex and took over part of the compiler’s work, and many of these explanations are simply wrong these days, but the basic patterns remain. Template functions and built-in functions can (and often should) fall into the header along with all of your shared declarations don't-direct-generate-object-code. The definition of normal functions should not be in the header file.

+3
source share

All Articles