我創建了一個全域檔案 (Globals.h) 來保存我的全域渲染器(gRenderer)和我的全域視窗(gWindow)。我將它們宣告為extern,因為它們將在InitChess.cpp 下的 initWindow()和initRenderer()函式中定義。
聯結器抱怨我有“未決議的外部符號”的某些原因,即使我在InitWindow.cpp下的函式中定義了它們。
錯誤:
Severity Code Description Project File Line Suppression State Error LNK2001 unresolved external symbol "struct SDL_Window * gWindow" (?gWindow@@3PEAUSDL_Window@@EA) Chess C:\Users\\source\repos\Chess\Chess\InitChess.obj
Severity Code Description Project File Line Suppression State Error LNK2001 unresolved external symbol "struct SDL_Renderer * gRenderer" (?gRenderer@@3PEAUSDL_Renderer@@EA) Chess C:\Users\\source\repos\Chess\Chess\InitChess.obj
國際象棋.cpp:
#include "SDL.h"
#undef main
#include <iostream>
#include "../include/InitChess.h"
int main()
{
InitChess* e = new InitChess;
e->initWindow();
e->initRenderer();
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
return 3;
}
delete e;
return 0;
}
初始化國際象棋.h:
#pragma once
#include "SDL.h"
#include "../include/Globals.h"
class InitChess {
public:
void initWindow();
void initRenderer();
~InitChess();
private:
};
初始化國際象棋.cpp:
#include "../include/InitChess.h"
void InitChess::initWindow()
{
SDL_Window* createdWindow;
createdWindow = SDL_CreateWindow(
"An SDL2 window", // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
640, // width, in pixels
480, // height, in pixels
SDL_WINDOW_OPENGL // flags
);
// assign created window to global window variable in Globals.h
gWindow = createdWindow;
}
void InitChess::initRenderer()
{
SDL_Renderer* createdRenderer;
createdRenderer = SDL_CreateRenderer(gWindow, -1, 0);
// assign created render to global renderer variable in Globals.h
gRenderer = createdRenderer;
}
InitChess::~InitChess()
{
SDL_DestroyRenderer(gRenderer);
SDL_Quit();
}
全域.h:
#pragma once
#include "SDL.h"
#ifndef GLOBALS_H
#define GLOBALS_H
extern SDL_Window* gWindow;
extern SDL_Renderer* gRenderer;
#endif
uj5u.com熱心網友回復:
宣告和定義是有區別的。
平時寫
SDL_Window* gWindow;
是變數的宣告和定義gWindow。
您的程式使用的每個(非行內)變數都可以有多個宣告,但必須只有一個定義。
放在extern前面SDL_Window* gWindow;使宣告不是定義。
因此,您仍然需要在gWindow某處定義。這在程式中只能出現一次,因此您不能將定義放在可能包含在多個.cpp檔案中的頭檔案中。
您需要選擇一個.cpp檔案并將定義放在SDL_Window* gWindow;那里。定義必須在全球范圍內,否則是指相同的變數宣告extern SDL_Window* gWindow;在Globals.h。
在您的代碼中,該檔案似乎應該是InitChess.cpp,但根據您的設計,創建 aGlobals.cpp并將定義放在那里可能會更好。
// assign created window to global window variable in Globals.h
gWindow = createdWindow;
這不是定義,甚至不是宣告。它只是一個賦值運算式。變數的宣告以它的型別名稱開始。但是如上所述,簡單地放在SDL_Window*這一行前面并不會定義在 中宣告的全域變數Globals.h。相反,它會在函式中宣告并定義一個新的同名區域變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409046.html
標籤:
下一篇:CodeLiteIDE未讀取檔案
