C++:"extern reference"宣言

C++: Declaration of "extern reference"

本文关键字:宣言 reference extern C++      更新时间:2023-10-16

我想将一个变量声明为 extern double& 并在static const struct中使用它的指针。在其他地方,我想将变量定义为另一个结构的成员。附加的代码如我预期的那样适用于x86

问题是它在嵌入式ARM上下文中不起作用:初始化static const struct内的void* void_pointer只有NULL,而其他所有内容看起来都有效。

我在这里尝试的语法是否可行并在标准中定义,或者定义了一些详细的实现?我将如何调试它?可能出现什么问题?这里到底发生了什么?

#include <iostream>
// declare and define place where the actual content is stored
struct storage_struct { double double_array[2]; double double_variable; };
struct storage_struct db = {{3.0,4.0},1.0};
// declare "double_reference" as extern
extern double &double_reference;
// declare and defince a struct to hold the pointer to the extern reference:
struct target_struct { void *void_pointer; };
static const struct target_struct dut { &double_reference };
// and now connect the "extern refernce" to an actual value from the database-struct
double &double_reference = db.double_variable;
int main() {
    std::cout << "testPrint with initial values:n";
    std::cout << "void pointer: '" << dut.void_pointer << "', value: '"
              << *(double *)dut.void_pointer << "'n";
    std::cout << "n";
    // change content in the database
    db.double_variable = 11.0;
    db.double_array[0] = 1444.0;
    db.double_array[1] = 238947.0;
    std::cout << "adress of storage_struct: " << &db << "n";
    std::cout << "adress of double_variable: " << &db.double_variable << "n";
    std::cout << "adress of double_reference: " << &double_reference << "n";
    std::cout << "n";
    std::cout << "testPrint with changed values:n";
    std::cout << "void pointer: '" << dut.void_pointer << "', value: '"
              << *(double *)dut.void_pointer << "'n";
    std::cout << "n";
    return 0;
}

编译和执行方式: g++ -std=c++11 -o test main.cpp && ./test -- 像魅力一样工作。将其闪存到 ARM μC -- void_pointer 0x00...(请注意,它也适用于 Debian ARM

有趣的是,这适用于 x86;我没想到会这样。 dut.void_pointerdouble_reference之前初始化,因为它首先在代码中定义。解决方法是颠倒实例化的顺序:

// first initialise the reference
double &double_reference = db.double_variable;
// then take the pointer, when it has a defined value.
static const struct target_struct dut { &double_reference };