extern "C" indicates to the C++ compiler that the function name should not be mangled. Since you're linking against an external library, the expectation is that the external library has a function (and only one function) called foo. The static keyword in C99 and onward in an array size tells the compiler that "this array will be at least this size", which may allow the compiler to make certain optimizations (I don't know what optimizations these could be, but consider that it could possibly do loop unrolling up to N = 4, where you declared void foo(int i[static 5]); If you pass an array that is not at LEAST this size, you could have a bad time.
The immediate solution is just that we need to tell the C++ compiler:
- There is a function called
foo
- It takes an
int * as a parameter
extern "C"
{
void foo(int i[]);
}
But we lose the information to anyone using this in the C++ program that this function MUST be at least size N (which is what the static keyword in the array size meant). I can't think of a good way to force a compile-time check on this except possibly through some type templated wrapper function:
#include <cstddef>
extern "C"
{
void foo(int i[]);
}
template <std::size_t N>
void c_foo(int i[N])
{
static_assert(N >= 5);
foo(i);
}
int main(int argc, char** argv)
{
int a[5] = {1, 2, 3, 4, 5};
int b[4] = {1, 2, 3, 4};
c_foo<5>(a); // this will be fine
c_foo<4>(b); // this will raise a compile-time error
}
To be extra safe, I'd put the function prototypes for your c_foo functions and any "safe" extern "C" prototypes in one c_library_interface.h file, and the function definitions for your c_foo functions and any "unsafe" extern "C" prototypes in another c_library_interface_unsafe.cpp file. That way, as long as you don't include the unsafe file in your main C++ files, you should only be able to interface with the static array size functions through the templates, which will do some size checking.
extern "C"only specifies a language binding, not magically teaches a C++ Compiler the language referred to.extern Cmeans, "Hey, don't mangle this name. This is the function signature as is". You shouldn't be actually DEFINING the function in theextern "C"block, right? You're just supposed to link to it? So you'd writeextern "C" { void foo(int i[]); }and make sure you link with the library. I don't do a lot (or any at all) interfacing with C libraries. I've just seen it in the past.statickeyword though. You shouldn't get that error at all.static 1specifically, it's redundant as Standard C and C++ do not support zero-sized arrays anyway. Perhaps this is supposed to indicate "pointer should not be a null pointer"