在C++中,"C"功能和"C"联动有什么区别?

In C++, what's the difference between a "C" function and a "C" linkage?

本文关键字:什么 区别 功能 C++      更新时间:2023-10-16

正如标准所述,语言链接是函数类型的一部分,cppReference给出了以下示例

extern "C" void f1(void(*pf)()); // declares a function f1 with C linkage,
// which returns void and takes a pointer to a C function
// which returns void and takes no parameters
extern "C" typedef void FUNC(); // declares FUNC as a C function type that returns void
// and takes no parameters
FUNC f2;            // the name f2 has C++ linkage, but its type is C function
extern "C" FUNC f3; // the name f3 has C linkage and its type is C function void()
void (*pf2)(FUNC*); // the name pf2 has C++ linkage, and its type is
// "pointer to a C++ function which returns void and takes one
// argument of type 'pointer to the C function which returns void
// and takes no parameters'"
extern "C" {
static void f4();  // the name of the function f4 has internal linkage (no language)
// but the function's type has C language linkage
}

我真的很困惑C函数类型和C链接。它们之间有什么区别,除了捣乱?具有C++链接的 C 函数是什么意思?谢谢!

更新:这不是问extern "C"做什么,因为这没有回答为什么 C 函数可以有C++链接,此外,是什么造就了 C 函数(C++内部),以及为什么std::qsortstd::bsearch必须有两个重载。

在您引用的例子中,"C 函数"表示"其类型具有 C 语言链接的函数"。

也许你没有在精神上区分这两个不同的概念:

  1. 函数类型的语言链接。
  2. 标识符的语言链接。

具有C++联动的 C 函数是什么意思?

我猜你指的是FUNC f2;函数类型具有 C 链接,而标识符f2具有C++链接。

我对 C

函数类型和 C 链接感到非常困惑。它们之间有什么区别,除了捣乱?

在标准C++中,"C 函数"和"C++函数"是不同的类型,就像intlong是不同的类型一样,即使INT_MAX == LONG_MAX。在许多实现中,类型的行为完全相同并不重要。重要的是,在某些实现中,类型的行为可能不同,因此所有实现都应将类型视为不同的类型。这意味着在标准C++中,

extern "C" void f();
void (*fp)() = &f; // ERROR

无效,因为初始化器与正在初始化的类型不兼容。"指向 C 函数的指针"和"指向C++函数的指针"之间没有隐式转换。

不能将 C 和 C++ 函数视为同一类型的实现的最现实的假设方案是对 C 与C++函数使用不同调用约定的实现。

具有C++联动的 C 函数是什么意思?

我猜这是关于

FUNC f2;            // the name f2 has C++ linkage, but its type is C function

这意味着调用函数的方式与调用 C 函数的方式完全相同,但名称被篡改以像往常一样包含函数参数信息等,从而允许它被重载。