【问题标题】:how do header implementation file get included in another c file头实现文件如何包含在另一个c文件中
【发布时间】:2017-04-17 12:04:35
【问题描述】:

如何在测试头文件中的方法的源文件中调用在头文件中实现方法的 c 源文件。我正在使用 Devc++ IDE 例如

sum.h
#ifndef SUM_H_
#define SUM_H_
   int add(int a, int b);
#endif

sum.c
#include"sum.h"
    int add(int a, int b){
  return a+b;
}

sumtest.c
#include "sum.h"
   int main(){
      int a = 10;
      int b = 10;
   printf("the sum of a and b is : %d", add(a, b));

   return 0;
 }

请代码仅用于说明。 所以在上面的代码中,sumtest.c 是如何知道 add 的实现的,即使 sumtest.c 中没有明确包含“#include sum.c”。

【问题讨论】:

  • 编译器在构建sumtest.c源文件时,会从头文件中看到声明(因为包含在内),知道有一个函数叫做@987654324 @某处。
  • 你为什么回滚编辑?有没有cmets?
  • @Sourav Ghosh 这是一个错误,不是故意感谢您的编辑。

标签: c compilation header-files


【解决方案1】:

头文件不是提供定义,而是前向声明。

引用C11,第 7.1.2 章

[...] header 声明一组相关函数,以及任何必要的类型和额外的宏 需要方便他们的使用。 [....]

也就是说,有four different stages of compilation,需要的其中两个大致描述如下

  • 编译:编译预处理的源文件以生成目标文件
  • 链接:将目标文件链接在一起以生成二进制文件(可执行文件)

不同的源文件(翻译单元不能相互“包含”,而是将它们编译并链接在一起形成二进制文件。编译(到目标文件)并链接在一起时,链接器会在 sum.o 和任何其他链接在一起的目标文件(反之亦然)中找到所需的 sumtest.o 引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2011-06-23
    相关资源
    最近更新 更多