是的extern" C"只需要在函数声明? [英] Is extern "C" only required on the function declaration?

查看:126
本文介绍了是的extern" C"只需要在函数声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个C ++函数,我需要从C程序调用。为了使由C来调用,我指定的的externC在功能上的声明。然后,我编译C ++ code,但是编译器(Dignus系统/ C ++)产生的重整名称的功能。因此,它显然没有兑现的externC

I wrote a C++ function that I need to call from a C program. To make it callable from C, I specified extern "C" on the function declaration. I then compiled the C++ code, but the compiler (Dignus Systems/C++) generated a mangled name for the function. So, it apparently did not honor the extern "C".

要解决这个问题,我添加的externC给函数的高清即可。在此之后,编译器生成的函数名是由C来调用

To resolve this, I added extern "C" to the function definition. After this, the compiler generated a function name that is callable from C.

从技术上来说,的externC只需要在函数声明中指定。这是正确的吗? (该 C ++ FAQ精简版有一个很好的例子。)如果你还需要指定它在功能上的定义?

Technically, the extern "C" only needs to be specified on the function declaration. Is this right? (The C++ FAQ Lite has a good example of this.) Should you also specify it on the function definition?

下面是证明这一点的例子:

Here's an example to demonstrate this:

/* ---------- */
/* "foo.h"    */
/* ---------- */

#ifdef __cplusplus
extern "C" {
#endif

/* Function declaration */
void foo(int);

#ifdef __cplusplus
}
#endif

/* ---------- */
/* "foo.cpp"  */
/* ---------- */

#include "foo.h"

/* Function definition */
extern "C"               // <---- Is this needed?
void foo(int i) {
  // do something...
}

我的问题可能是不正确的编码东西的结果,否则我可能已经找到一个编译器错误。在任何情况下,我想咨询下计算器,以确保我知道这在技术上是正确的方式。

推荐答案

的externC'不应该在功能上确定指标,只要需要的声明有它,并已出现在确定指标的编制。该标准明确规定(7.5 / 5联动规格):

The 'extern "C"' should not be required on the function defintion as long as the declaration has it and is already seen in the compilation of the defintion. The standard specifically states (7.5/5 Linkage specifications):

一个函数可以没有明确的链接规范已经看到后,链接规范声明;在原先的声明中明确指定的联动不受这样的函数声明。

A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.

不过,我一般把的externC'上把定义为好,因为它实际上是在与外部的C联动的功能。很多人讨厌不必要的,多余的东西是声明(就像把虚拟的方法覆盖),但我不是其中之一。

However, I generally do put the 'extern "C"' on the defintion as well, because it is in fact a function with extern "C" linkage. A lot of people hate when unnecessary, redundant stuff is on declarations (like putting virtual on method overrides), but I'm not one of them.

这篇关于是的extern&QUOT; C&QUOT;只需要在函数声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆