【问题标题】:Access a static array defined in another cxx file访问另一个 cxx 文件中定义的静态数组
【发布时间】:2020-08-21 04:08:37
【问题描述】:

我有一个链接到共享库的程序。这个库包含一个 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 文件或在我的代码中复制数组?

提前致谢。

【问题讨论】:

  • 在代码中包含 cxx 是个坏主意,不要这样做...
  • 共享库必须有函数。他们有没有访问并返回这个数组?
  • 有些人访问它(在 cxx 中)但没有人返回它。

标签: c++ arrays static extern


【解决方案1】:

在一个translation unit 中使用static linkage 定义的变量(在某种程度上)是该翻译单元的“私有”。

没有其他翻译单元可以访问该变量。

所以不,不可能直接访问该数组。

作为一种变通方法,您可以考虑创建一个类,并将数组放入该类中。然后您可以使用成员函数以间接方式访问该类。如果您只想要一个数组实例(而不是类的每个对象实例一个),那么您可以在类中设置为 static

【讨论】:

    【解决方案2】:

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

    随机文件.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 之外没有其他翻译单元会知道数组大小。

    干杯, 调频。

    【讨论】:

    • 我不想这样做,因为它是一个大图书馆,我不是它的作者。
    猜你喜欢
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2014-12-03
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2010-12-30
    相关资源
    最近更新 更多