我试图组织我的项目所以我认为我将在global.h头中包含我的所有全局变量#includes和struct definition。但是我无法完全理解这个概念,并且构建期间的错误似乎证明了这一点。当我尝试在logic.h中访问我的global.h时,会发生这种情况。
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)) ===|
我不确定我错过了什么。谢谢你的建议!
答案 0 :(得分:0)
当你include "global.h"
时,其中一个第一个事情就是include "logic.h"
,所以处理器会打开该文件,找到一个include "global.h"
,它什么都不做因为包含守卫,然后它找到void initCharacter(Character &newCharacter,
并且因为它还不知道Character
是什么而感到困惑。然后它返回包含,lexes enum directions
,然后最后 lexes struct Character
,所以然后它知道Character
是什么,太晚了。
一般来说,尽量确保只包含一种方式。请确保logic
包含global
,或global
包括logic
,但不能同时包含global
。
或者,如果你真的很懒,有一个技巧有时会回避这个问题:尽可能经常地在包含之前放置函数和类定义。然后class Character
将告诉编译器logic.h
存在,然后当它包含#ifndef GLOBAL_H
#define GLOBAL_H
enum directions;
struct Character; //If you're really lazy, this usually works
#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
{
...
时,它就不会有问题。
void generate(){
std::vector<std::thread> threads;
for(size_t i=0; i<10; i++){
threads.push_back(std::thread(move_column_blocks, 1, 2));
threads.push_back(std::thread(move_column_blocks, 2, 3));
}
for(auto& t : threads)
t.join();
}