【问题标题】:Can I use extern function declaration on a C Header which is also used for the C source file which contains the function definition?我可以在 C Header 上使用 extern 函数声明,它也用于包含函数定义的 C 源文件吗?
【发布时间】:2020-02-10 13:28:02
【问题描述】:

我在 C89 中有以下源代码:

routine_a.c

struct DataRoutineA routineA(int a, int b) {
  struct DataRoutineA data = (struct DataRoutineA *) malloc(sizeof(DataRoutineA));
  data.a = a;
  data.b = b;
  return data;
}

以及以下头文件:

routine_a.h

struct DataRoutineA {
  int a;
  int b;
};

extern struct DataRoutineA routineA(int a, int b);

routine_a.h 的目的是它可以用作其他源代码文件的标头。因此定义了结构以及外部函数定义。在那种情况下,我的理解是标题已正确定义。

但是,如果此标头也用于routine_a.c,extern 子句会发生什么情况?在 ANSI C/C89 中解决这个问题的方法是什么?这种情况下我需要两个不同的标题吗?

【问题讨论】:

  • 在routine_a.c 中包含routine_a.h 是完全有效的。相反,gcc 可以选择在翻译单元中定义的非静态函数的 no extern 声明时创建警告
  • “extern”子句不会搞砸什么吗? -我试图在 K&R The C Programming Language 书中找到对这个案例的引用,但没有成功-
  • 不,它不会弄乱任何东西。

标签: c header-files c89


【解决方案1】:

默认情况下,C 中的所有函数都是外部函数。所以没有区别

extern struct DataRoutineA routineA(int a, int b);

struct DataRoutineA routineA(int a, int b);

在声明函数原型时,您确实需要 extern 关键字。

【讨论】:

  • 所以我可以删除 extern 子句并在 routine_a.croutine_x.c 中使用标题。那么extern子句只适用于变量呢?
  • 是的——但不完全是。正如我所写,函数是默认的外部函数 - 所以不需要 extern 关键字,并且两个定义完全相同。
猜你喜欢
  • 2022-10-14
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-24
相关资源
最近更新 更多