Header files and include best practice

后端 未结 2 1231
慢半拍i
慢半拍i 2021-01-18 14:28

I have a quick question regarding header files, include statements, and good coding style. Suppose I have 2 classes with associated source and header files, and then a fina

2条回答
  •  独厮守ぢ
    2021-01-18 15:12

    You should include all necessary files in every file that needs them. If MyProgram.cpp needs string, include it, instead of relying on it being included by Bar.hpp. There's no guarantee 2 weeks from now Bar.hpp will still include it, and then you'll be left with compiler errors.

    Note the necessary - i.e. make sure you actually need an include, when a forward declaration or even leaving it out completely will do.

    Also, note that some system headers might include others - apart from a few exceptions, there's no requirement. So if you need both and include both, even if you can compile only with one of them.

    The order in which the includes appear (system includes vs user includes) is up to the coding standard you follow - consistency is more important than the choice itself.

提交回复
热议问题