c - 在 main() 中声明的函数是否具有外部链接或无链接?

标签 c function external extern linkage

请参阅以下代码:

/* first file */

int i; /* definition */
int main () {
  void f_in_other_place (void);   /* declaration */
  i = 0
  return 0;
}
/* end of first file */


/* start of second file */

extern int i; /* declaration */
void f_in_other_place (void){   /* definition */
  i++;
}
/* end of second file */
我知道外部对象有external链接和内部对象有 none链接(暂时忽略 extern)。现在,如果我谈论功能 f_in_other_place() , 它在 main 函数中声明。那么它的标识符会被视为内部对象吗?如果是,则应该有 none链接,但在程序中可见,此函数指的是它在第二个文件中的定义,该文件显示它的标识符表现得像一个带有 external 的对象。链式。所以我很困惑这里的标识符是否有 external联动或none联动?
现在来到extern关键字,我在某处读到函数声明隐含前缀 extern .所以即使我没有提到 extern对于这个函数标识符,默认情况下我的函数标识符会变成一个带有 external 的对象吗?链接和范围内 main() ?如果我走错了方向,请纠正我。

最佳答案

I know that external objects have external linkage and internal objects have none linkage


我认为术语“内部对象”是指在块作用域中声明的对象。
至于这个声明
int i; /* definition */
那么它就是一个声明。你可以一个接一个地放置几个这样的声明,比如
int i; /* definition */
int i; /* definition */
int i; /* definition */
编译器在翻译单元的末尾生成该变量的所谓暂定定义,将其初始化为零。
至于 main 中的函数声明,则根据 C 标准(6.2.2 标识符的链接)

5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.



4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.


所以这个函数在 main 中声明
void f_in_other_place (void);
相当于
extern void f_in_other_place (void);
由于文件范围内没有先前的函数声明,因此该函数具有外部链接。
例如,如果在 main 之前的文件范围中,将会有一个带有关键字 static 的声明。喜欢
static void f_in_other_place (void);
那么 main 中声明的函数将具有内部链接。

关于c - 在 main() 中声明的函数是否具有外部链接或无链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64388332/

相关文章:

c - 关于 int 未定义增量的警告

c - linux GCC中结构的重新定义

swift - 定时器只执行一次函数

c - 如何创建函数指针的动态数组?

go - 如何在 Golang 上通过 IPC 为 OpenLDAP 客户端实现 SASL/EXTERNAL?

c - 如何在数组中使用int?

c++ - 将 if 语句与指针一起使用时出现段错误(BST 树)

function - 为什么有些?在 Clojure 中将 false 作为参数时返回 true?

jquery - 如何将jquery Mustache应用到外部文件/模板

android - 如何将位于第三方应用程序或浏览器(如 whatsapp 消息)的 url 直接打开到我的 webview 应用程序中?