Writing function definition in header files in C++

后端 未结 7 1518
孤城傲影
孤城傲影 2020-11-30 20:00

I have a class which has many small functions. By small functions, I mean functions that doesn\'t do any processing but just return a literal value. Something like:

相关标签:
7条回答
  • 2020-11-30 20:38

    C++ won’t complain if you do, but generally speaking, you shouldn’t.

    when you #include a file, the entire content of the included file is inserted at the point of inclusion. This means that any definitions you put in your header get copied into every file that includes that header.

    For small projects, this isn’t likely to be much of an issue. But for larger projects, this can make things take much longer to compile (as the same code gets recompiled each time it is encountered) and could significantly bloat the size of your executable. If you make a change to a definition in a code file, only that .cpp file needs to be recompiled. If you make a change to a definition in a header file, every code file that includes the header needs to be recompiled. One small change can cause you to have to recompile your entire project!

    Sometimes exceptions are made for trivial functions that are unlikely to change (e.g. where the function definition is one line).

    Source: http://archive.li/ACYlo (previous version of Chapter 1.9 on learncpp.com)

    0 讨论(0)
提交回复
热议问题