簡體   English   中英

C ++:“外部引用”的聲明

[英]C++: Declaration of “extern reference”

我想將變量聲明為extern double&並在static const struct使用它的指針。 我想在其他地方將變量定義為實際上是另一個結構的成員。 正如我所期望的那樣,附加的代碼可在x86上運行。

問題是它在嵌入式ARM上下文中void* void_pointer在初始化的static const structvoid* 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 };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM