哪些平台对C和c++有不兼容的abi ?

What platforms have incompatible ABIs for C and C++?

本文关键字:不兼容 abi c++ 平台      更新时间:2023-10-16

我刚刚注意到c++标准规定C和c++函数具有不同且不兼容的类型,即使它们的类型签名相同(更多信息请参阅这个问题)。这意味着技术上不允许将c++函数传递给像pthread_create()这样的C函数。

我很好奇在使用的平台中是否有两个abi实际上是不同的(除了明显的名称混淆差异)。具体来说,有没有人知道这个c++程序在哪些平台上无法编译和运行?

#include <assert.h>
extern "C" int run(int (*f)(int), int x) { return f(x); }
int times2(int x) { return x * 2; }
int main(int argc, char *argv[]) {
  int a = times2(argc);
  // This is undefined behavior according to C++ because I am passing an
  // "extern C++" function pointer to an "extern C" function.
  int b = run(&times2, argc);
  assert(a == b);
  return a;
}

我不知道有哪个平台的ABI不同,但即使C和c++调用约定相同,c++标准也要求编译器为程序发出诊断。带有c语言链接的指向函数的指针与带有c++语言链接的指向函数的指针是不同的类型,因此您应该能够像这样重载run():

extern "C" int run(int (*f)(int), int x) { return f(x); }
extern "C++" int run(int (*f)(int), int x) { return f(x); }

现在,当你调用run(times)时,它应该调用第二个,因此,第一个是不可调用的(没有从c语言链接的指针到函数到c++语言链接的指针到函数的转换),因此原始代码应该引起编译器诊断。但是,大多数编译器会出错,例如http://gcc.gnu.org/bugzilla/show_bug.cgi?id=2316

注意:Solaris编译器诊断不兼容的语言链接,作为警告:

"t.c", line 11: Warning (Anachronism): Formal argument f of type extern "C" int(*)(int) in call to run(extern "C" int(*)(int), int) is being passed int(*)(int).

如果用extern "C++"函数重载run,它会正确地为run(times)调用extern "C++"函数。