在C++中,"C"功能和"C"联动有什么区别?
In C++, what's the difference between a "C" function and a "C" linkage?
正如标准所述,语言链接是函数类型的一部分,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::qsort
,std::bsearch
必须有两个重载。
在您引用的例子中,"C 函数"表示"其类型具有 C 语言链接的函数"。
也许你没有在精神上区分这两个不同的概念:
- 函数类型的语言链接。
- 标识符的语言链接。
具有C++联动的 C 函数是什么意思?
我猜你指的是FUNC f2;
函数类型具有 C 链接,而标识符f2
具有C++链接。
我对 C
函数类型和 C 链接感到非常困惑。它们之间有什么区别,除了捣乱?
在标准C++中,"C 函数"和"C++函数"是不同的类型,就像int
和long
是不同的类型一样,即使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 函数的方式完全相同,但名称被篡改以像往常一样包含函数参数信息等,从而允许它被重载。
相关文章:
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- Qt:remove() 和 rmdir() 有什么区别
- 这 4 个 lambda 表达式之间有什么区别?
- 将向量作为类>(值)<向量启动和向量<类>[值]有什么区别
- typedef 枚举和枚举类有什么区别?
- &C::c 和 &(C::c) 有什么区别?
- ascii 和 unicode 在处理级别有什么区别吗?
- C 中的常量限定符和 C++ 中的常量限定符有什么区别?
- "ABC" 和 "ABC" ) 在C++中有什么区别?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 引用捕获和在 lambda 中通过引用发送参数有什么区别 (C++)
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 这两种C++语法之间有什么区别?
- lua 5.0.2 模块和 5.3.5 有什么区别?
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- std::enable_if 和 std::enable_if_t 有什么区别?