我試圖組織我的項目,所以我想我會包括我的全局變量,#includes和結構定義在global.h頭文件中。然而,我無法完全理解這個概念,而構建過程中的錯誤似乎證明了這一點。當我嘗試在logic.h中訪問我的global.h時,會發生什麼情況。在單獨的頭文件中的C++結構
global.h:
#ifndef GLOBAL_H
#define GLOBAL_H
#include "logic.h"
#include <SDL.h>
#include <iostream>
#include <string>
#include "graphics.h"
//Global variables and structs
enum directions
{
D_UP,
D_LEFT,
D_DOWN,
D_RIGHT,
D_TOTAL
};
struct Character
{
float health;
float x;
float y;
float velocity;
bool collision[D_TOTAL];
directions direction;
SDL_Rect animation;
SDL_Rect sprite;
};
const int windowWidth = 800;
const int windowHeight = 600;
const int frameWidth = 64;
const int frameHeight = 64;
#endif // GLOBAL_H
logic.h:
#include "global.h"
//Header for gamelogic functions
//Initialization of all variables for a new character
void initCharacter(Character &newCharacter, float x, float y, directions startingDirection);
當我嘗試構建它,這是我得到的錯誤:
||=== Build: Debug in GameProject0.2 (compiler: GNU GCC Compiler) ===|
C:\Users\Rafał\Documents\GameProject0.2\GameProject0.2\logic.h|5|error: variable or field 'initCharacter' declared void|
C:\Users\Rafał\Documents\GameProject0.2\GameProject0.2\logic.h|5|error: 'Character' was not declared in this scope|
C:\Users\Rafał\Documents\GameProject0.2\GameProject0.2\logic.h|5|error: 'newCharacter' was not declared in this scope|
C:\Users\Rafał\Documents\GameProject0.2\GameProject0.2\logic.h|5|error: expected primary-expression before 'float'|
C:\Users\Rafał\Documents\GameProject0.2\GameProject0.2\logic.h|5|error: expected primary-expression before 'float'|
C:\Users\Rafał\Documents\GameProject0.2\GameProject0.2\logic.h|5|error: 'directions' was not declared in this scope|
||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
我不知道我錯過了什麼。感謝您的任何建議!
謝謝,但我認爲它清楚地說#include「global.h」在logic.h文件中。我認爲這會完成這項工作,但不知何故:( –
@RafałMyśliwczyk你還在global.h文件中包含了logic.h。當你包含包含global.h的logic.h時,你會怎麼想呢?包括logic.h,其中包含global.h,其中包括logic.h,其中包含global.h,其中包括logic.h,其中包含global.h,其中包含logic.h,其中包含global.h,其中包含logic.h,其中包含global.h包括logic.h,其中包含global.h,其中包含logic.h,其中包含global.h,其中包含logic.h,其中包含global.h,其中包含logic.h,其中包含global.h,其中包含logic.h ...? – user2079303
A關於避免循環依賴和使用[包括守衛](https://en.wikipedia.org/wiki/Include_guard)的良好警示性的故事。兩個爲一個的價格。 – user4581301