Search code examples
c++arraysstaticextern

Access a static array defined in another cxx file


I have a program that links to a shared library. This library includes a RandomFile.cxx file, which has an array definition like this:

static double randomArray[] = {0.1, 0.2, 0.3};

In the header file RandomFile.hxx of RandomFile.cxx, there is no extern, getter, or anything regarding the randomArray.

In my program, I want to somehow access this array.

So far I have tried:

// sizeOfRandomArray was calculated by counting the elements.
int sizeOfRandomArray = 3;

// 1st attempt: does not compile because of undefined reference to the array
extern double randomArray[sizeOfRandomArray];

// 2nd attempt: does not compile because of undefined reference to the array
extern "C" double randomArray[sizeOfRandomArray];

// 3rd attempt: does not compile because of undefined reference to the array
extern "C++" double randomArray[sizeOfRandomArray];

// 4th attempt: compiles but i don't get the actual values
extern "C" {
double randomArray[sizeOfRandomArray];  
}

// 5th attempt: compiles but i don't get the actual values
extern "C++" {
double randomArray[sizeOfRandomArray];
}

// 6th attempt: compiles and works but I overload my code with the whole RandomFile.cxx file.
#include "RandomFile.cxx"

I can't(don't want to) change the RandomFile.cxx because it is part of a big library named VTK.

Is there any possible way to do it, without including the cxx file or copying the array in my code?

Thanks in advance.


Solution

  • A variable defined with with static linkage in one translation unit is (in a way) "private" to that translation unit.

    No other translation units can access that variable.

    So no it't not possible to access that array directly.

    As a work-around you might consider creating a class, and put the array inside the class. Then you could use member-functions to access the class in an indirect way. If you only want one instance of the array (and not one per object instance of the class) then you can make it static in the class.