C ++:" extern reference"

时间:2014-11-21 12:50:55

标签: c++ c++11 struct extern

我想将变量声明为extern double&并在static const struct中使用它的指针。在其他地方,我想将变量定义为实际上是另一个struct的成员。附加的代码正如我所期望的那样在x86上工作。

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

我在这里尝试的语法是否可以在标准中定义,或者定义了一些详细的实现?我该怎么调试呢?什么可能出错?这里到底发生了什么?

#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

1 个答案:

答案 0 :(得分:0)

有趣的是,这适用于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 };