2016-12-15 83 views
-2

讓說我內MyTools.h如何定義「全局」結構?

#ifndef _MYTOOLS_ 
#define _MYTOOLS_ 

typedef struct { 
    // const 
    double LN20; 
    double LN40; 

    // methods 
    double NoteToFrequency(int noteNumber); 
} Tool; 

extern const Tool tool; 

#endif // !_MYTOOLS_ 

decleared這對於每個編譯單元中,只有一個全球性的/常量/獨特的Tool實例。正是我想要的。

但現在:我該如何定義它?在.h我只宣佈它。我如何在.cpp中定義它?試過一些像這樣的:

tool.LN20 = 1.34; 

但當然它不起作用。該方法的定義?

+1

related/dupe:http://stackoverflow.com/questions/20716091/global-const-object-shared-between-compilation-units – NathanOliver

+2

'const Tool tool {1.34,3.14};'?工作示例:[這裏](https://ideone.com/xiiJ2e)。 –

+1

順便說一下,那些標記爲「// const」的成員實際上並不是*常量。 –

回答

-1

extern沒有定義它只是聲明它的任何變量。你wan't什麼來實現,可以按以下步驟進行:

鏈接Global const object shared between compilation units介紹如何使用EXTERN常量做

個文件

#ifndef _MYTOOLS_ 
#define _MYTOOLS_ 

struct Tool { 
    // const 
    double LN20; 
    double LN40; 
    double NoteToFrequency(int noteNumber); 

} ; 

extern const Tool tool ; 

#endif // !_MYTOOLS_ 

t1.cpp

#include "t.h" 
#include <stdio.h> 

void use_tool() 
{ 
    printf("%f\n",tool.LN20); 
    printf("%f\n",tool.LN40); 
    return; 
} 

t2.cpp

#include "t.h" 
#include <stdio.h> 


const Tool tool = {.LN20 = 20.0, .LN40 = 30.2}; 
double Tool::NoteToFrequency(int noteNumber) 
{ 
    return 12.0; 
} 
void use1_tool() 
{ 
    printf("%f\n",tool.LN20); 
    printf("%f\n",tool.LN40); 
    return; 
} 
int main() 
{ 
    void use_tool(); 
    use_tool(); 
    use1_tool(); 
    return 0; 
} 

希望這有助於。

+0

我不想要它!由於它是'const',因此默認情況下它變爲'static',因此每個編譯單元的結構的2個不同的立即數。 – markzzz

+0

是的,所以刪除了extern關鍵字,它應該按照您的需要工作。 –

+0

不!我想要extern(即唯一的實例) – markzzz