C: Why do we include header files, which declare but don't define?

后端 未结 5 674
迷失自我
迷失自我 2021-01-14 07:59

At a high level, I understand we use #include statements to make code from other files available to the current file. But I don\'t understand why we include a h

5条回答
  •  旧巷少年郎
    2021-01-14 08:40

    why we include a header file, which contains declarations but no definitions.

    Let's say we have a file

    header.h

    extern void func();
    

    And this function is defined in some file f1.c and will be called by f2.c then include the required header to notify the compiler that the function definition exists in some other file without including the header the compiler will not know what the call to func() is within main()

    f1.c

    void func()
    {
    }
    

    f2.c

    #include "header.h"
    int main()
    {
      func();
    }
    

    There can be multiple declarations but there can't be multiple definitions for the same function

提交回复
热议问题