2013-03-09 40 views
0

我有這個簡單的例子,我無法得到它來編譯:LNK2001錯誤使用的extern INT

三個文件:my.hmy.cppuse.cpp

//my.h 
extern int foo; 
void print_foo(); 
void print(int); 

//my.cpp 
#include "my.h" 
#include "../../stb_lib_facilities.h" //inlcudes cout, cin, etc 

void print_foo(){ 
    cout << foo << endl; 
} 

void print(int i){ 
    cout << i << endl; 
} 

//use.cpp 
#include <iostream> 
#include "my.h" 

int main(){ 
    foo = 7; 
    print_foo(); 
    print(99); 

    return 0; 
} 

當我嘗試編譯它,我得到三個錯誤: LNK2001:外部的 「INT富」 .. LNK2019:外部的 「INT富」 .. LNK1120:

我在做什麼錯? 感謝您的任何幫助

回答

5

您沒有任何定義您的全局變量。在任何,只是在他們一個.cpp文件,你應該補充一點:

int foo = 0; // This is a definition 

聲明

extern int foo; // This is a declaration 

只告訴這樣一個全局變量存在的編譯器,但是那裏沒有你實際定義它的地方。因此,鏈接器最終會抱怨你有一個未定義的引用符號。

+0

謝謝!足夠清晰 – 2013-03-09 22:24:00

+0

@nachogsiri:很高興能幫到你 – 2013-03-09 22:26:58