1

ヘッダー ファイルの宣言で変数を外部化し、対応する cpp ファイルで再度宣言する必要があるのはなぜですか。

を。リンクエラー防止

    ex. header 1.h-
    namespace forglobal { 
    extern int x;
    }

     source 1.cpp- 
    namespace forglobal{
    int x=6;
    }

    source 2.cpp- 
    #include "1.h"
    cout<<x; //6

b. 別の cpp ファイルで使用します。関数 ex を呼び出すように名前空間を使用することはできません。

    header -1.h
    namespace forglobal {
    int x
    }

    source -1.cpp {
    namespace forglobal {
    void change() {
    x=5;
    }
    }
    }

    source -2.cpp 
    #include "1.h"
    forglobal::change();
    cout<<forglobal::x<<'\n'; //5
4

3 に答える 3