简体   繁体   English

C和C ++中类型的互操作性

[英]Interoperability of types in C and C++

A very simple question: are there any guarantees that a C int is the same thing as a C++ int , on the same system? 一个非常简单的问题:在同一系统上,是否有任何保证C int与C ++ int是同一个东西?

It goes without saying that this is, of course, a purely theoretical question. 毫无疑问,这当然是纯粹的理论问题。

The C and C++ standards use the same language to define the fundamental types. C和C ++标准使用相同的语言来定义基本类型。 But whereas Fortran 2003 makes it clear that 但Fortran 2003明确表示

use ISO_C_BINDING
integer(kind=c_int) :: i

declares an integer type which is compatible with the int type on a "companion C processor", I can't find any such assertion in the C++ stardard. 声明一个与“伴随C处理器”上的int类型兼容的整数类型,我在C ++标准中找不到任何这样的断言。 It seems very odd that Fortran would provide stronger C interoperability guarantees than C++! Fortran提供比C ++更强大的C互操作性保证似乎很奇怪!

The closest I can find is section 7.5 [dcl.link], paragraph 3 of the C++11 standard, which states that 我能找到的最接近的是7.5节[dcl.link],C ++ 11标准的第3段,其中指出了这一点

Every implementation shall provide for linkage to functions written in the C programming language 每个实现都应提供与用C编程语言编写的函数的链接

But this little sentence doesn't (to me) seem strong enough to guarantee compatibility of fundamental types. 但是这个小句子(对我而言)似乎不足以保证基本类型的兼容性。

Is there some other language in the C++ standard that I've overlooked which guarantees this, or is it just so obviously taken for granted that no-one has bothered to state it explicitly? C ++标准中是否有其他一些我忽略的语言可以保证这一点,或者它是否显然被认为是理所当然的,没有人打扰明确说明它?

EDIT : David Schwartz in the comments points out that I was imprecise when I said "the same system". 编辑 :大卫施瓦茨在评论中指出,当我说“同一系统”时,我是不精确的。 I really meant the same "platform", ie hardware, OS, system libraries etc. It's really an ABI issue of course. 我真的是指同一个“平台”,即硬件,操作系统,系统库等。当然,它确实是一个ABI问题。 In the quoted passage the C++ standard seems to want to indicate that you can call C functions with extern "C" , but I'm not sure if it provides enough other guarantees? 在引用的段落中,C ++标准似乎想表明你可以使用extern "C"调用C函数,但我不确定它是否提供了足够的其他保证?

No. 没有。

There are widely used conforming compilers on x64 amd compatible cpus that treat long as 32 bit and others as 64 bit by default. 在x64 amd兼容的cpus上广泛使用的符合编译器,默认情况下long 32位,其他为64位。 So this is not even the case for two C++ compilers on the same system, let alone a C++ and C compiler. 因此,对于同一系统上的两个C ++编译器来说,情况甚至不是这样,更不用说C ++和C编译器了。

Within one compiler, that is up to the compiler vendor if they are compatible. 在一个编译器中,如果它们兼容,则由编译器供应商决定。 They usually (always) are. 他们通常(总是)。 "one compiler" is a bit of a misnomer here: the C snd C++ compilers are different compilers, even if in the same binary by the same vendor, in a sense. “一个编译器”在这里有点用词:C snd C ++编译器是不同的编译器,即使在同一个供应商的同一个二进制文件中,在某种意义上。

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

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