使用 extern "C" 进行重载解析连锁 [英] Overload resolution with extern "C" linkage

查看:72
本文介绍了使用 extern "C" 进行重载解析连锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在混合 C/C++ 项目中,我们需要从 C 调用 C++ 函数.要调用的函数被重载为三个独立的函数,但我们可以从 C 端忽略它,我们只选择最合适的一个并坚持那个.

In a mixed C/C++ project, we need to make a call from C to a C++ function. The function to be called is overloaded as three separate functions, but we can ignore that from the C-side, we just pick the one most suitable and stick to that one.

有两种方法可以做到这一点:(1) 编写一个带有 extern "C" 函数的小型 C++ 包装器,将调用转发到所选的重载函数,或者 (2) 只声明我们想要的一个函数从 C 调用为 extern "C".

There's two ways to do this: (1) write a small C++ wrapper with a extern "C" function that forwards the call to the chosen overloaded function, or (2) the hackish way to just declare the one function we want to call from C as extern "C".

问题是,第二个变体是否有任何缺点(除了噩梦和恶业)?换句话说,给定三个重载函数,其中一个被声明为 exern "C",我们应该期待 C++ 方面的麻烦,还是根据标准定义得很好?

The question is, is there any disadvantages (apart from nightmares and bad karma) to go for the second variant? In other words, given three overloaded function, where one is declared as exern "C", should we expect trouble with the C++ side, or is this well defined according to the standard?

推荐答案

我相信标准中的语言是专门编写的,只允许一个具有C"链接的函数,以及任意数量的具有C++"链接的其他函数重载同名 (§[dcl.link]/6):

I believe the language in the standard is specifically written to allow exactly one function with "C" linkage, and an arbitrary number of other functions with "C++" linkage that overload the same name (§[dcl.link]/6):

至多一个具有特定名称的函数可以具有 C 语言链接.出现在不同命名空间作用域中的具有相同函数名称(忽略限定它的命名空间名称)的具有 C 语言链接的函数的两个声明引用同一个函数.出现在不同命名空间范围内的具有相同名称的 C 语言链接的对象的两个声明(忽略限定它的命名空间名称)引用同一个对象.

At most one function with a particular name can have C language linkage. Two declarations for a function with C language linkage with the same function name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same function. Two declarations for an object with C language linkage with the same name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same object.

标准显示以下示例:

complex sqrt(complex); // C + + linkage by default
extern "C" {
    double sqrt(double); // C linkage
}

这篇关于使用 extern "C" 进行重载解析连锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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