C++ 中的外部函数

发布于 2024-11-13 09:04:33 字数 189 浏览 2 评论 0原文

当在 cpp 文件中外部函数时,编译器是否会以不同的方式处理这些函数?

extern void foo(char * dataPtr);  
void foo(char *);
extern void foo(char * );  

我很想知道,因为我在代码中看到了所有这些,但不确定有什么区别。

When externing a function in the cpp file does the compiler treat these differently?

extern void foo(char * dataPtr);  
void foo(char *);
extern void foo(char * );  

I am wondering because I have see all these in code and not sure what the difference is.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清风不识月 2024-11-20 09:04:33

具体情况:

 extern void foo(char * dataPtr);  

函数默认具有外部链接,因此不需要 extern - 这相当于:

 void foo(char * dataPtr);

参数名称在函数声明中并不重要,因此上面相当于:

 void foo(char * );  

使用您觉得最满意的那个。

Case by case:

 extern void foo(char * dataPtr);  

functions have external linkage by default, so the extern is not necessary - this is equivalent to:

 void foo(char * dataPtr);

Parameter names are not significant in function declarations, so the above is equivalent to:

 void foo(char * );  

Use whichever you feel happiest with.

从﹋此江山别 2024-11-20 09:04:33

不,它们都是相同的功能。只有一个函数,即具有此签名:

void foo(char *);

其他两个函数的存在没有区别,无论有或没有关键字extern,因为函数名称默认具有外部链接。

No. They all are same functions. There is only one function, namely with this signature:

void foo(char *);

Presence of other two makes no difference, with or without the keyword extern, as function names have external linkage by default.

何其悲哀 2024-11-20 09:04:33

extern 是 C++ 函数的默认链接。这三个声明之间没有区别。

extern is the default linkage for C++ functions. There's no difference between those three declarations.

痴情 2024-11-20 09:04:33

不,它们是一样的。所有函数声明都是外部的。 extern 关键字表示“我想让您知道它存在,但我不会在这里定义它。”对于 int,这是必要的,因为声明也是定义。对于函数,末尾的分号明确地将其标记为此处未定义。

我对他们为什么将其标记为 extern 的最佳猜测可能是因为函数声明位于头文件中,但定义并不像人们通常期望的那样位于相应的 c 文件中。这类似于 extern 通常在 int 类型上使用的方式(您想要声明它,但您计划从其他源链接它)。因此它是一种文档形式。

这是对我来说链接的最佳解释:

http://publications.gbdirect.co .uk/c_book/chapter4/linkage.html

No, they are the same. All function declarations are external. The extern keyword says "I want to let you know this exist, but I'm not defining it here." With an int, this would be necessary, because a declaration is also a definition. With a function, the semicolon at the end is explicitly marking it as not defined here.

My best guess as to why they marked it extern is possibly because the function declaration is in the header file but the definition is not in the corresponding c file as one would usually expect. This is similar to how extern is usually used on an int type (where you want to declare it but you plan to link it in from some other source.) So it's a form of documentation.

This is the best explanation of linkage to me:

http://publications.gbdirect.co.uk/c_book/chapter4/linkage.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文