Home > Net >  In C CLI, how to use/declare a static int array accessible to all functions in the source file?
In C CLI, how to use/declare a static int array accessible to all functions in the source file?

Time:06-30

In C /CLI, how to declare the C equivalent of "static int array[400]" where array is accessible to all functions in the source file -- without getting the error "a member of a managed class cannot be a standard array"?

A non-array declaration, like "static int age", works fine, but not arrays.

CodePudding user response:

C doesn't actually have any notion of "source file". Instead there's a "compilation unit" which consists of the file that the compiler starts processing (because it was specified on the command-line) AND all files found from that file via #include, recursively.

In C you can use exactly the same syntax that worked in C:

static int array[400];

but it's preferred to use an anonymous namespace rather than global-scoped static:

namespace
{
    int array[400];
}

Note that you shouldn't be putting these lines inside of a class or ref class block, they go at file scope. And they shouldn't be in a header file, which is where most class or ref class definitions are found, because header files are intended to be included into multiple compilation units and doing that will lead to having a bunch of independent copies of the same variable, which is bound to cause confusion.


If on the other hand your need is not related to compilation units at all, and you want a variable shared between all member functions in the class, no matter where they may be defined or #included, then you should use a static data member. In C /CLI, a data member of a managed class has to be itself managed data, so use the C /CLI syntax for a .NET array:

cli::array<int>^ array = gcnew cli::array<int>(400);

For static data members of managed types, C /CLI acts more like C# than C and you can write the initial value inline:

ref class MyCppCliClass
{
    static cli::array<int>^ array = gcnew cli::array<int>(400);
};
  • Related