I don't understand why I am getting an unresolved external symbol in this specific example.
I have a Rectangle struct defined in a header file.
I have a Level class which has a pointer to a Player class as the Level creates a new player.
I my Player class, the constructor takes in a pointer to it's current level.
So since my Level includes Player.h I forward declare Level in my Player class to prevent a circular reference.
However, when I try and add a Rectangle member variable to my Player class - I get the unresolved external symbol error, but I can't see why - since the Player class includes the header - and the definition is in the header. It works fine in my Level class.
Also - if I change the member variable to a pointer it links fine.
Can someone explain to me why this is the case and how I can fix the issue?
// Rectangle.h
#pragma once
namespace Test
{
struct Rectangle
{
public:
Rectangle();
Rectangle(
int x,
int y,
int width,
int height) :
X(x),
Y(y),
Width(width),
Height(height)
{
}
int X;
int Y;
int Width;
int Height;
};
}
// Level.h
#pragma once
#include "Player.h"
#include <memory>
namespace Test
{
class Level
{
public:
Level()
{
_player.reset(new Player(this));
};
private:
std::unique_ptr<Player> _player;
};
}
// Player.h
#pragma once
#include "Rectangle.h"
namespace Test
{
class Level;
class Player
{
public:
Player(
Level* currentLevel) :
_currentLevel(currentLevel)
{
}
private:
Level* _currentLevel;
// This line causes the issue
Rectangle _localBounds;
};
}
You forgot to add braces on your Rectangle constructor. Make it like this:
Rectangle() {}
So the problem is you have the definition but not the implementation. You can indeed declare a function without braces but it is like you make a promise to the compiler that you are going to add the function's body somewhere else. That's why separating classes to .hpp and .cpp files works.
Note: Retired Ninja gave the answer first in a comment below the post.
Related
The IDE I am using is Microsoft Visual Studio 2022 and I am following a guide for game development.
I have the following code:
//Game.h
#pramga once
class Game{
public:
Game();
static int mapWidth;
};
//Game.cpp
#include "Game.h"
//Initialization
int Game::mapWidth;
//Implementation class
Game::Game(){
mapWidth = 10;
};
//Camera.h
#pragma once
#include "Game.h"
class Camera{
Camera() = default;
void update(){
if (Game::mapWidth > 0)
//do something
}
};
What is interesting is that if I hover over this variable in Camera.h the IDE recognizes the variable and where its coming from. But, when i go to compile i get the following error from my if statement:
C2653 'Game': is not a class or namespace name
I am using the scope resolution operator and my vairable is public static and initialized in Game.cpp/h. So, why am I getting this compile error when the IDE recognizes the variable and the Game class as existing?
You seem to be missing a trailing semicolon at the end of your Game class definition. Definitions of structs and classes in C++, unlike in other languages, end in closing bracket AND a semicolon. Such an error might be hard to spot (depending on your IDE). When the preprocessor includes Game.h in Game.cpp, it puts it right above the initialization of Game::mapWidth, which causes it to get invalidated.
Proper definition should like this:
class Game {
public:
static int mapWidth;
Game(); // <-- declaration of constructor should be here
}; // <-- note the semicolon
This is the case for your Camera class as well.
class Camera{
if (Game::mapWidth > 0)
//do something
}; // Semicolon
After searching on nearly every page covering this error, I couldn't find a solution that matched my problem. When including the header file for the base class in the file of the derived class, I get the error: "error C2504: 'Entity': base class undefined". I have three classes, a parent class, derived class, and an inbetween class that both of the other classes need access to. I'm making an entity class for my enemies and other entities to inherit from, but even after including its header, I still get the error. I've tried forward declarations for the parent class and they don't seem to do anything to no avail. Before looking at my code, ignore common.h, player.h, skeleton.h, game.h, and resourcemanager.h. Without futher ado, here is my code:
(Entity.h)
#include "Common.h"
#include "Tile.h";
class Entity {
public:
Tile *isSideColliding(bool isSolid, string&& type);
Tile* isTopColliding(bool isSolid, string&& type);
Tile* isBottomColliding(bool isSolid, string&& type);
Sprite sprite;
RectangleShape topHitbox, bottomHitbox;
};
(Slime.h)
#pragma once
#include "Common.h"
#include "Game.h"
#include "Entity.h"
#include "Tile.h"
#include "ResourceManager.h"
class Slime: public Entity {
public:
static vector<Slime> slimeVector;
Slime(float& x, float& y);
static void draw();
static void update();
private:
static const Vector2f SPRITE_DIMENSIONS;
char dir;
//Sprite sprite;
//RectangleShape topHitbox, bottomHitbox;
/*Tile* isSideColliding(bool isSolid, string&& type);
Tile* isTopColliding(bool isSolid, string&& type);
Tile* isBottomColliding(bool isSolid, string&& type);*/
static const float GRAVITY;
static const Vector2f TERMINAL_VELOCITY;
Vector2f position, velocity;
};
(Tile.h)
#pragma once
#include "Common.h"
#include "Player.h"
#include "Skeleton.h"
#include "ResourceManager.h"
#include "Chest.h"
#include "Slime.h"
class Slime;
class Player;
class Skeleton;
class Tile {
public:
Sprite sprite;
static void draw();
static void createLevelPathing();
static void setupBackground();
static vector<Tile> tileVector;
Vector2f spriteDimensions;
bool isSolid;
string type;
private:
Tile(float& x, float& y, string&& type, bool isSolid);
Tile(int& x, int& y, bool isSolid);
static void initTiles(int& levelPosX, int& levelPosY, const Image& image);
static Image getRoomTemplate(int& templateType);
static const float POSITION_SCALAR, SCALE;
static const int START_TILE, DOWN_TILE, UP_TILE, UP_AND_DOWN_TILE, DOOR_TILE;
};
My goal is to inherit from entity to slime. I'm fairly sure my file setup is good though. Could anyone please help explain why I'm getting the error of no base class defined? Also, I would appreciate critisism on my file including and how I could better structure it. Thanks!
As Jerry pointed out in the comment, it is circular include.
This normally implies that something can be improved in the design.
For example, why does the Entity has to care about the colliding logic? Can it instead expose some functions for the Tile module to calculate colliding?
Come back to your question. I suggest to:
In Entity, forward declare the Tile class. Move the #include "tile.h" to the .cpp file. Do the same for Slime.
In Tile, remove the #include and forward declaration for Entity and Slime, it seems they're completely unused there.
Again, I still believe it is better to rethink the flow and the responsibility of classes, which one does what. From what I can remember, circular dependencies will likely bite us later.
I'm working on a simple game C++ game using the SFML library. This is one of my first endeavors with C++ and I'm running into some problems with defining structs in headers.
Here is the bullet.h:
#pragma once
#include <SFML\Graphics.hpp>
struct BulletTransform {
sf::RectangleShape shape;
//details
BulletTransform(float, float);
};
class Bullet {
//class definition stuff, no problems here
then I try to create an implementation in the bullet.cpp file:
#include "Bullet.h"
struct BulletTransform {
sf::RectangleShape shape;
BulletTransform::BulletTransform(float mX, float mY)
{
//constructor for shape stuff
}
};
Now when I try to compile it throws an error saying struct in the bullet.cpp being a type redefinition. I understand that I cannot define a struct with the same name twice, but I am also not sure how I can fix this issue. Do I somehow need to get a reference to the definition in the header? Or is my implementation simply wrong? Thanks in advance!
In the header file you can make the declaration. In the source file the definition - thats the rule of thumb in general. In your case for example:
in bullet.h:
struct BulletTransform {
sf::RectangleShape shape;
// cntr
BulletTransform(float mX, float mY) ;
// other methods
void Function1(float x, float y, float z);
};
in bullet.cpp:
BulletTransform::BulletTransform(float mX, float mY) {
// here goes the constructor stuff
}
void BulletTransform::Function1(float x, float y, float z) {
// ... implementation details
}
Normally you don't do some heavy stuff in the constructor - just the initialization of data members for example to some default values.
Hope this helps.
You've repeated your struct definition in your implemenation file. Don't do that. Instead, provide definitions for the individual members, like this:
#include "Bullet.h"
BulletTransform::BulletTransform(float mX, float mY)
{
//constructor for shape stuff
}
I have seen other people asking this question before, but the answers they received were unique to their programs and unfortunately do not help me.
Firstly, I have a shape class - split into .h and .cpp files
//Shape.h
#include <string>
using namespace std;
class Shape
{
private:
string mColor;
public:
Shape(const string& color); // constructor that sets the color instance value
string getColor() const; // a const member function that returns the obj's color val
virtual double area() const = 0;
virtual string toString() const = 0;
};
//Shape.cpp
#include "Shape.h"
using namespace std;
Shape::Shape(const string& color) : mColor(NULL) {
mColor = color;
}
string Shape::getColor() const
{
return mColor;
}
I keep getting an error in my Shape.h class that says 'Shape' : 'class' type redefinition.
Any idea why I might be getting this error?
add include guard to your header file
#ifndef SHAPE_H
#define SHAPE_H
// put your class declaration here
#endif
And the way you initialize member mColor is incorrect. You can't assign NULL to string type
Shape::Shape(const string& color) : mColor(color) {
}
Add virtual destructor to Shape class as it serves as a base with virtual functions.
Also, do NOT use using directive in header file.
It seems like you want to write an abstract base class here, but is there any other files you compiled but not showed here?
You must include “shape.h” twice more.
Just use macros to prevent this case.
PS:I guess Rectangle is base class of Square,and also inherited Shape.
So I'm trying to get class "Herder" to inherit from class "Mob". But I am getting compiler errors that read as follows:
error: invalid use of incomplete type 'struct Mob'
error: forward declaration of 'struct Mob'
This is what Herder.h looks like:
#ifndef HERDER_H_INCLUDED
#define HERDER_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Level.h"
#include "Mob.h"
class Mob;
class Herder : public Mob
{
public:
//Member functions.
Herder(Level* level, int x, int y);
void virtual GameCycle(sf::RenderWindow* App);
void virtual Die();
void Roar();
protected:
float m_RoarCountdown;
float m_RoarTime;
float m_Speed;
bool m_Roaring;
};
#endif // HERDER_H_INCLUDED
Figuring that it must be the class Mob; that is causing this, I remove it, but then I get the following error, refering to the line where the curly braces open:
error: expected class-name before '{' token
This is actually why I originally added the forward declaration - I had thought that the compiler wasn't recognizing Mob in class Herder : public Mob, so I figured I would forward declare.
I don't think it's a case of cyclical dependency, as has been the case in some cases I found via Google - "Mob.h" contains nothing to do with the Herder class whatsoever.
I have tried removing #include "Mob.h" altogether and sticking with just the forward declaration, but that doesn't work either - I get only one error, again:
error: invalid use of incomplete type 'struct Mob'
This is confusing. I've successfully gotten classes to inherit before, and this code seems analogous in all relevant ways to my previous successful attempts.
EDIT: Here are the contents of Mob.h
#ifndef MOB_H_INCLUDED
#define MOB_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Level.h"
class Level;
class Mob
{
public:
//Member functions.
Mob(Level* level, int x, int y);
float GetX();
float GetY();
void SetColor(sf::Color color);
void virtual GameCycle(sf::RenderWindow* App) = 0;
void virtual Die() = 0;
void Draw(sf::RenderWindow* App);
protected:
float m_X;
float m_Y;
bool m_Moving;
int m_Health;
sf::Sprite m_Sprite;
Level* pLevel;
};
#endif // MOB_H_INCLUDED
EDIT: Here are the contents of the "Level.h" file. Note that Baby is a child class of Mob in much the same way as Herder; both experience the same errors.
#ifndef LEVEL_H_INCLUDED
#define LEVEL_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Tile.h"
#include "Herder.h"
#include "Baby.h"
class Tile;
class Herder;
class Baby;
/// LEVEL
/// This is the collection of all data regarding a level, including layout, objects, mobs, and story elements.
///
class Level
{
public:
//Constructor
Level(int height, int width, std::string name);
//For obtaining positional data
int GetHeight();
int GetWidth();
std::string GetName();
sf::Image GetTileImage(int image);
sf::Image GetMobImage(int image);
std::vector< std::vector<Tile> >& GetGrid();
void NewHerder(int x, int y);
void NewBaby(int x, int y);
void GameCycle(sf::RenderWindow* App);
void GraphicsCycle(sf::RenderWindow* App);
private:
//Size
int m_Height;
int m_Width;
//Spatial coords
std::string m_Name;
//The grid of tiles.
std::vector< std::vector<Tile> > m_Grid;
//A vector of the images to be used for tiles.
std::vector<sf::Image> m_TileImages;
//A vector of the images to be used for tiles.
std::vector<sf::Image> m_MobImages;
//The herders
std::vector<Herder> m_Herders;
//The babies
std::vector<Baby> m_Babies;
};
#endif // LEVEL_H_INCLUDED
EDIT: Pre-emptively, here are the contents of Tile.h:
#ifndef TILE_H_INCLUDED
#define TILE_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Level.h"
class Level;
/// TILE
/// This is the basic environmental unit in the game
///
class Tile
{
public:
//Constructor
Tile(int col, int row, int size, int type, Level* level);
//For obtaining positional data
int GetX();
int GetY();
int GetRow();
int GetCol();
//For obtaining type data
int GetType();
//For obtaining string type data
std::string GetStringType();
//For changing type data
void SetType(int type);
void SetStringType(std::string character);
//For activities that regularly take place
void GameCycle();
//Draws the tile.
void Draw(sf::RenderWindow* App);
private:
//The level this tile belongs to.
Level* m_Level;
//Size (it's a square!)
int m_Size;
//Spatial coords
int m_X;
int m_Y;
//Grid coords
int m_Row;
int m_Col;
//Type
int m_Type;
//Visual data
sf::Sprite m_Tile;
};
#endif // TILE_H_INCLUDED
It is a cyclic dependency (Herder.h includes Level.h which includes Herder.h, etc.).
In Herder.h, simply replace this :
#include "Level.h"
with :
class Level;
and do the same in Mob.h
The general rule is to include as little header files as possible (ie. only the ones you need). If you can get by with a forward declaration eg., then use that rather than a full include.
The problem you have is a cyclic dependency which is a code smell. On the one side, to be able to derive from a type, the base definition must be available to the compiler (i.e. the compiler requires a fully defined type from which to inherit). On the other hand your base class depends on the derived class.
The technical answer is to forward declare the derived type (so that you can define the base), and then define the base. But you should really think on what you are doing: why are those two separate types related by inheritance? Why not one? Or three (split responsibilities)? If the base depends on the derived for it's own interface, that seems to indicate that they are too highly coupled. Rethink the design.
"Herder.h" and "Level.h" are #include in each other. So, I think this error is coming from the "Herder.h" which is included first. It's becoming cyclic. Remove that and see if the error goes away.