0

コンパイラからこのエラーが発生します:

1>Linking...
1>main.obj : error LNK2005: "int g_win_flags" (?g_win_flags@@3HA) already defined in init.obj
1>main.obj : error LNK2005: "struct SDL_Surface * g_screen" (?g_screen@@3PAUSDL_Surface@@A) already defined in init.obj
1>MSVCRTD.lib(cinitexe.obj) : warning LNK4098: defaultlib 'msvcrt.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
1>.\Debug\Heroes are back!.exe : fatal error LNK1169: one or more multiply defined symbols found

g_win_flagsとg_screenが2回含まれているように見えますが、その理由がわかりません。ソースは次のとおりです。

main.cpp

#include <iostream>
#include "dec.h"
#include "init.h"

int main(int argc, char *argv[]){

    init();
    return 0;
}

dec.h

#ifndef DEC_H
#define DEC_H

#include <SDL.h>
#include <iostream>

#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")

using namespace std;

int g_win_flags = SDL_HWSURFACE|SDL_DOUBLEBUF;

SDL_Surface *g_screen = NULL;

#endif

init.h

#ifndef INIT_H
#define INIT_H

bool init();

#endif

init.cpp

#include "dec.h"

bool init(){
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == -1){
        cerr << "Unable to initialize SDL" << endl;
        return false;
    }
    g_screen = SDL_SetVideoMode(640, 480, 0, g_win_flags);

    return true;
}

誰かが助けることができますか?よろしくお願いします。良い一日を。

4

4 に答える 4

3

ヘッダーで変数を定義して初期化します。

イニシャライザなしでヘッダー(dec.h)で宣言する必要があります。

extern int g_win_flags;
extern SDL_Surface *g_screen;

次に、初期化を使用して、それらを1つのファイル(おそらくdec.cpp)で1回定義します。

それがそうであったように、あなたは「dec.h」を含むすべてのソースファイルでそれらを定義し、次にODRのファウルを実行していました-1つの定義規則。

于 2010-11-03T18:27:20.947 に答える
2

dec.hであなたが望む

extern int g_win_flags;

extern SDL_Surface *g_screen;

そして、それらをdec.cppで定義して初期化します。

アップデート:

#include "dec.h"
int g_win_flags = SDL_HWSURFACE|SDL_DOUBLEBUF;

SDL_Surface *g_screen = NULL;

一般的な経験則は、「ヘッダーファイル内の何もコンパイラの出力内のスペースを占有してはならない」というものです。(これには明らかに例外があります)

実際には、これは、関数宣言と同様に外部変数宣言が適切であることを意味しますが、定義は問題ありません。

于 2010-11-03T18:25:55.717 に答える
0

インスタンス化された変数を定義する2つの異なるソースファイル(init.cppとmain.cpp)にファイルを含めました。

1つのソースファイルを除くすべてのファイルでそれらが「外部化」されていることを確認する方法が必要です。

于 2010-11-03T18:26:15.020 に答える
0

さて、私はあなたが私に言ったことをやろうとしました、しかしコンパイル者は不平を言っています:

1>.\heroes are back!\dec.cpp(2) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\heroes are back!\dec.cpp(4) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\heroes are back!\dec.cpp(4) : error C2040: 'g_screen' : 'int' differs in levels of indirection from 'SDL_Surface *'

これがdec.hです

#ifndef DEC_H
#define DEC_H

#include <SDL.h>
#include <iostream>

#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")

using namespace std;

extern int g_win_flags;

extern SDL_Surface *g_screen;

#endif

dec.cpp

#include "dec.h"
g_win_flags = SDL_HWSURFACE|SDL_DOUBLEBUF;

g_screen = NULL;

このコードの何が問題になっていますか?ばかげた質問をして申し訳ありませんが、私はC++を学んでいるだけです:)

于 2010-11-03T18:46:57.367 に答える