首页 > 解决方案 > 访问另一个 cxx 文件中定义的静态数组

问题描述

我有一个链接到共享库的程序。这个库包括一个 RandomFile.cxx 文件,它有一个这样的数组定义:

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

在 RandomFile.cxx 的头文件 RandomFile.hxx 中,没有任何关于 randomArray 的 extern、getter 或任何东西。

在我的程序中,我想以某种方式访问​​这个数组。

到目前为止,我已经尝试过:

// 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"

我不能(不想)更改 RandomFile.cxx,因为它是名为VTK的大库的一部分。

有没有办法做到这一点,而不包括 cxx 文件或在我的代码中复制数组?

提前致谢。

标签: c++arraysstaticextern

解决方案


如果不修改 RandomFile.cxx,就无法访​​问该对象。只需删除staticRandomFile.cxx 文件中的说明符并将对象声明为extern公共头 RandomFile.hxx 或需要访问的目标翻译单元。这使得对象具有外部链接的静态持续时间:

随机文件.hxx:

 constexpr int sizeOfRandomArray=3
 extern double randomArray[sizeOfRandomArray];

随机文件.cxx:

 double randomArray[sizeOfRandomArray] {1,2,3};

请参阅: https ://en.cppreference.com/w/cpp/language/storage_duration

请记住,如果您错过了声明中的大小,除了 RandomFile.cxx 之外没有其他翻译单元会知道数组大小。

干杯,调频。


推荐阅读