简体   繁体   English

“extern C ++”如何工作?

[英]How does “extern C++” work?

I jumped into winnt.h and I found out the code as following: 我跳进了winnt.h ,发现代码如下:

extern "C++" // templates cannot be declared to have 'C' linkage
template <typename T, size_t N>
char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];

I'd like to ask questions as following: 我想问一下如下问题:

  1. how does extern "C++" work? extern "C++"如何工作?
  2. is this portable among GCC, and Clang? 这是GCC中的便携式和Clang吗?
  3. can all templates be exported with this syntax? 是否可以使用此语法导出所有模板?

With question 3, I mean that can I separate declearation and definition of the templates, and then generate a dynamic link for the template without actually give the implementation by using this trick? 对于问题3,我的意思是我可以将模板的declearation和定义分开,然后为模板生成动态链接,而不使用这个技巧实际给出实现吗?

Well, extern "C++" won't work in C, of course (though some compilers might support it as an extension). 那么, extern "C++"当然不适用于C(虽然有些编译器可能会支持它作为扩展)。 So it only makes sense to use it in C++. 所以在C ++中使用它才有意义。

That's because in the case of multiple nested extern linkage specifiers, the innermost one takes effect. 这是因为在多个嵌套的extern链接说明符的情况下,最里面的一个生效。 So if you have a header file surrounded with extern "C" , you can use extern "C++" to temporarily break out of it and declare something with C++ linkage. 因此,如果你有一个用extern "C"包围的头文件,你可以使用extern "C++"暂时中断它并用C ++链接声明一些东西。

It makes the most sense when you want to provide a generally C interface for a C++ library, but you also want to provide C++ helper bits for people actually using it in C++. 当你想为C ++库提供一个通用的C接口时,它是最有意义的,但你也想为在C ++中实际使用它的人提供C ++帮助位。 So you'd put #ifdef __cplusplus \\ extern "C" { \\ #endif around the header as a whole, and then you ifdef-in those bits with extern "C++" to revert to C++ linkage. 因此,你将#ifdef __cplusplus \\ extern "C" { \\ #endif整个标题放在标题周围,然后你将ifdef-in这些位用extern "C++"恢复为C ++链接。

  1. It works by forcing the compiler to use C++ linkage when the surrounding code uses C linkage by default (eg, you include winnt.h in a C program). 它的工作原理是当周围的代码默认使用C链接时强制编译器使用C ++链接(例如,在C程序中包含winnt.h)。
  2. Yes, it should be portable. 是的,它应该是便携式的。
  3. Yes they can. 是的他们可以。 There is not much use for "extern "C++"" in C++ programs because the linkage is "C++" anyway. 在C ++程序中“extern”C ++“”没什么用处,因为无论如何链接都是“C ++”。 It makes sense to use "extern "C++"" only if there is a good chance that your C++ code will be included into a C code. 只有当你的C ++代码很有可能被包含在C代码中时才使用“extern”C ++“”是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM