Flexible array members are a standard feature of C, starting with the 1999 standard. They do not exist in 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.
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.
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[];
^
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.)
(I'm assuming that you're using g++. Some other compilers probably implement similar extensions.)