2014-11-21 96 views
0

我想聲明一個變量爲extern double&並在static const struct中使用它的指針。我想在其他地方定義變量實際上是另一個結構的成員。如我所料,附帶的代碼適用於x86C++:「外部引用」聲明

問題是,它並沒有在嵌入式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

回答

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 }; 
+0

這就是爲什麼變量首先聲明爲'extern double&'。鏈接器將連接它們。在這個測試的另一個版本中,不同的部分分佈在不同的編譯單元上 - 這也適用於x86 – user3520187 2014-11-21 13:03:11

+0

如果變量分佈在多個翻譯單元中,那麼您會長時間運行靜態初始化命令失敗。鏈接器找到引用,是的,但由於引用初始化時可能尚未初始化引用,所以指針的值未指定。 – seldon 2014-11-21 13:26:20

+0

因此,將'static const struct dut'移動到某個init函數中可以解決μC方面的實際問題**謝謝!**但是我不確定*靜態初始化順序失敗是我真正的問題。在我的問題中發佈的代碼是在_one_恩,並不能在μC上工作...並沒有構造函數調用...? – user3520187 2014-11-21 14:22:32