请问用C的extern C ++避免不确定的行为是合法的C,但不是C ++? [英] Does extern C with C++ avoid undefined behavior that is legal in C but not C++?

查看:160
本文介绍了请问用C的extern C ++避免不确定的行为是合法的C,但不是C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用外部C 使用C ++文件它,是否允许定义在C ++未定义行为ç?

If you use extern C it with C++ files, does that allow defined C behavior that is undefined in C++?

blah.h

 extern "C"
 {
      struct x {
           int blah;
           char buf[];
      };

      char * get_buf(struct x * base);
      struct x * make_struct(int blah, int size);
 }

some_random.cpp

some_random.cpp

 #include "blah.h"

 ...

 x * data=make_struct(7, 12);
 std::strcpy(get_buf(data), "hello");

时当使用C灵活的阵列成员定义的行为,定义的行为以这种方式使用的时候?

Is using the defined behavior in C's flexible array member, defined behavior when used this way?

推荐答案

灵活数组成员是C的标准功能,从1999年的标准。他们不会在C ++中存在。

Flexible array members are a standard feature of C, starting with the 1999 standard. They do not exist in C++.

您code是无效的C ++。在的externC结束语不改变。标准的C ++编译器的必须的至少警告它,可以说的的拒绝。

Your code is not valid C++. Wrapping it in extern "C" doesn't change that. A conforming C++ compiler must at least warn about it, and arguably should reject it.

碰巧G ++实现C风格灵活的阵列成员扩展到C ++。这是完全合法的(编译器被允许执行扩展),但它的使用是不可移植。它的行为,就像任何语言扩展,是由编译器定义的,而不是由语言。

It happens that g++ implements C-style flexible array members as an extension to C++. That's perfectly legitimate (compilers are allowed to implement extensions), but its use is not portable. Its behavior, like that of any language extension, is defined by the compiler, not by the language.

如果您 G ++ -pedantic 编译它,你会得到一个警告:

If you compile it with g++ -pedantic, you'll get a warning:

c.cpp:5:21: warning: ISO C++ forbids zero-size array ‘buf’ [-Wpedantic]
            char buf[];
                     ^

如果你想用C风格灵活的阵列成员C ++程序不依赖于特定的编译器扩展,可以编译C code的为C 的,并将其链接到您的C ++程序。你不能让与灵活的阵列成员到C ++ code可见的类型,但是你可以在C code内部使用它,也许通过提供在C ++ code对它的访问不透明的指针。请参见 C ++的常见问题解答大约在同一程序中混合使用C和C ++的信息。 (或者你可以使用G ++的扩展,在不能够与其它编译器来编译code的成本。)

If you want to use C-style flexible array members in a C++ program without relying on a compiler-specific extension, you can compile your C code as C and link it into your C++ program. You can't make the type with the flexible array member visible to your C++ code, but you can use it internally in the C code, and perhaps provide access to it in your C++ code via an opaque pointer. See the C++ FAQ for information about mixing C and C++ within the same program. (Or you can just use the g++ extension, at the cost of not being able to compile your code with other compilers.)

(我假设你使用G ++。其他一些编译器可能实施类似的扩展。)

(I'm assuming that you're using g++. Some other compilers probably implement similar extensions.)

这篇关于请问用C的extern C ++避免不确定的行为是合法的C,但不是C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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