静态对外部“C”/“C ++” [英] static vs extern "C"/"C++"

查看:212
本文介绍了静态对外部“C”/“C ++”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态成员函数和外部C链接函数之间有什么区别?例如,当在C ++中使用makecontext时,我需要传递一个指向函数的指针。谷歌建议使用externC链接,因为makecontext是C.但我发现使用静态工作以及。我只是幸运或...

What is the difference between a static member function and an extern "C" linkage function ? For instance, when using "makecontext" in C++, I need to pass a pointer to function. Google recommends using extern "C" linkage for it, because "makecontext" is C. But I found out that using static works as well. Am I just lucky or...

class X {
   public:
   static void proxy(int i) {}
}
makecontext(..., (void (*)(void)) X::proxy, ...);

vs

extern "C" void proxy(int i) {}
makecontext(..., (void (*)(void)) proxy, ...);

编辑:对不起,我还是不相信...你可以显示一个编译器

I am sorry, but I'm still not convinced... Can you show a compiler or architecture where the static member version does not work (and it's not a bug in the compiler) ?

推荐答案

是的,你是只是幸运:) externC是C语言的一种语言链接,每个C ++编译器都必须支持,除了externC ++这是默认值。编译器可以支持其他语言链接。 GCC例如支持externJava,它允许与java代码连接(虽然这很麻烦)。

Yes, you are just lucky :) The extern "C" is one language linkage for the C language that every C++ compiler has to support, beside extern "C++" which is the default. Compilers may supports other language linkages. GCC for example supports extern "Java" which allows interfacing with java code (though that's quite cumbersome).

externC告诉编译器,您的函数可以通过C代码调用。这可以但不一定包括适当的调用约定和适当的C语言名称调整(有时称为装饰)等等,这取决于实现。如果你有一个静态成员函数,它的调用约定是你的C ++编译器之一。通常它们与该平台的C编译器相同 - 所以我说你只是幸运。如果你有一个C API并且传递一个函数指针,最好总是把一个放到用externC声明的函数,如

extern "C" tells the compiler that your function is callable by C code. That can, but not must, include the appropriate calling convention and the appropriate C language name mangling (sometimes called "decoration") among other things depending on the implementation. If you have a static member function, the calling convention for it is the one of your C++ compiler. Often they are the same as for the C compiler of that platform - so i said you are just lucky. If you have a C API and you pass a function pointer, better always put one to a function declared with extern "C" like

extern "C" void foo() { ... }

即使函数指针类型不包含连接规范,但看起来像

Even though the function pointer type does not contain the linkage specification but rather looks like

void(*)(void)

链接是类型的一个组成部分 - 你不能直接表达它没有typedef:

The linkage is an integral part of the type - you just can't express it directly without a typedef:

extern "C" typedef void(*extern_c_funptr_t)();

Comeau C ++编译器在严格模式下会发出错误,例如,如果您尝试分配地址的上面的externC函数到(void(*)()),因为这是一个指向C ++链接的函数。

The Comeau C++ compiler, in strict mode, will emit an error for example if you try to assign the address of the extern "C" function of above to a (void(*)()), beause this is a pointer to a function with C++ linkage.

这篇关于静态对外部“C”/“C ++”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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