What's the benefit for a C source file include its own header file

前端 未结 5 1363
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 07:49

I understand that if a source file need to reference functions from other file then it needs to include its header file, but I don\'t understand why the source file include

5条回答
  •  攒了一身酷
    2020-12-29 08:38

    The main benefit is having the compiler verify consistency of your header and its implementation. You do it because it is convenient, not because it is required. It may definitely be possible to get the project to compile and run correctly without such inclusion, but it complicates maintenance of your project in the long run.

    If your file does not include its own header, you can accidentally get in a situation when forward declaration of a function does not match the definition of the function - perhaps because you added or removed a parameter, and forgot to update the header. When this happens, the code relying on the function with mismatch would still compile, but the call would result in undefined behavior. It is much better to have the compiler catch this error, which happens automatically when your source file includes its own header.

提交回复
热议问题