使用外部“C”时是否与大括号有区别吗? [英] Is there a difference between with braces or without when using extern "C"?

查看:134
本文介绍了使用外部“C”时是否与大括号有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在被James Kanze和Loki Astari教授关于C链接的学习时,我想知道这一点: p>

So, while being schooled by James Kanze and Loki Astari about C linkage, I was wondering about this:

extern "C" int foo1 (void (*)());
extern "C" { int foo2 (void (*)()); }

在我上学后,我认为一定是 foo1 只接受一个带有C ++链接的函数指针,而 foo2 只接受一个带C链接的函数指针。我的理解是正确的吗?在C ++标准中有没有具体的参考资料来解释我上面的例子中的区别?

After my schooling, I think it must be that foo1 only takes a function pointer with C++ linkage, while foo2 only takes a function pointer with C linkage. Is my understanding correct? Are there specific references in the C++ standard that explain the differences in my example above?

编辑 这里是一个包含C ++ 11草稿标准的相关部分的pastebin

推荐答案

foo1使用指向C函数的指针,如[dcl.link]中所示。7.5p4

foo1 takes a pointer to a C function as shown in [dcl.link] 7.5p4


指定的语言链接适用于
所有函数声明符的函数类型,具有
外部链接的函数名称和变量名称外部链接在链接规范中声明为
[Example:

externCvoid f1(void(* pf)(int)); code>

                                                                     并且其函数类型具有C语言

                                                                     > // linkage; pf是指向C函数的指针

extern "C" void f1(void(*pf)(int));
                                                                 // the name f1 and its function type have C language
                                                                 // linkage; pf is a pointer to a C function

示例直接应用于 foo1 和添加的强调突出我认为是的原因。函数的参数列表包含参数的函数声明符,所有函数声明符都受连接规范的影响。

The example applies directly to foo1 and the added emphasis highlights what I think is the reason. The function's parameter lists contains a function declarator for a parameter, and all function declarators are affected by the linkage specification. This applies to both braced and non-braced linkage specifications.

不使用大括号时的一些区别是,名称会自动 extern

Some differences when not using braces are that names are automatically extern and explicit use of a storage specifier is prohibited.

extern "C" int i; // not a definition

int main() {
    i = 1; // error, no definition
}

extern "C" static void g(); // error

作为差异重要的例子,考虑一个包含以下内容的标题: p>

As an example of where this difference matters, consider a header containing the following:

extern "C" int a;
extern "C" double b;
extern "C" char c;

有人可能会试图将其更改为:

Someone might be tempted to change this to:

extern "C" {
    int a;
    double b;
    char c;
}

但是这不正确,因为将声明转换为定义。而是使用 externC{} 的正确代码是:

But that would be incorrect because that converts the declarations into definitions. Instead the correct code using extern "C" {} is:

extern "C" {
    extern int a;
    extern double b;
    extern char c;
}

这篇关于使用外部“C”时是否与大括号有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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