问题描述
我有一个链接到共享库的程序。该库包含一个RandomFile.cxx文件,该文件的数组定义如下:
static double randomArray[] = {0.1,0.2,0.3};
在RandomFile.cxx的头文件RandomFile.hxx中,没有任何extern,getter或与randomArray有关的任何内容。
在我的程序中,我想以某种方式访问此数组。
到目前为止,我已经尝试过:
// 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文件或复制数组?
谢谢。
解决方法
在一个linkage中用static
translation unit定义的变量(在某种程度上)是该翻译单元的“专用”。
没有其他翻译单位可以访问该变量。
因此,不可能直接访问该数组。
作为一种变通办法,您可以考虑创建一个类,然后将数组放入该类中。然后,您可以使用成员函数以间接方式访问该类。如果只需要数组的一个实例(而不是该类的每个对象实例一个),则可以在类中将其设为static
。
如果不修改RandomFile.cxx,就无法访问该对象。
只需删除RandomFile.cxx文件中的static ILog& logger() {
// this ONLY works if GetLogger always returns the same object
return CMyLog::GetLogger("log_name");
}
说明符,然后在公共标头RandomFile.hxx或需要访问的目标转换单元中将对象声明为static
即可。这使得对象具有外部链接的静态持续时间:
RandomFile.hxx:
extern
RandomFile.cxx:
constexpr int sizeOfRandomArray=3
extern double randomArray[sizeOfRandomArray];
请参阅: https://en.cppreference.com/w/cpp/language/storage_duration
请记住,如果您错过了声明的大小,则除RandomFile.cxx之外的其他翻译单元都不会知道数组的大小。
干杯, FM。