1

この簡単な例があり、コンパイルできません。

3 つのファイル: my.hmy.cpp、およびuse.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;
}

コンパイルしようとすると、次の 3 つのエラーが発生します: LNK2001: extern "int foo".. LNK2019: extern "int foo".. LNK1120:

私は何を間違っていますか?助けてくれてありがとう

4

1 に答える 1

6

グローバル変数の定義がありません。どのファイルでも、ただしそのうちの1 つ.cppだけに、これを追加する必要があります。

int foo = 0; // This is a definition

あなたの宣言

extern int foo; // This is a declaration

そのようなグローバル変数が存在することをコンパイラに伝えるだけですが、実際にそれを定義する場所はありません。したがって、リンカは最終的に未定義の参照シンボルがあると文句を言うでしょう。

于 2013-03-09T22:15:15.493 に答える