Advertisement Jump to content

Include order not working (c++)

Recommended Posts


I get this error. And im pretty sure it has to do with some include order or circular include.

Error    1    error C2079: 'cRegion::a' uses undefined class 'army'

This is from the world.h file that starts like this:

#pragma once

#include "unit.h"
#include "main.h"
#include "cWalker.h"
#include "pathMaster.h"

#include "player.h"

class army;
class armyUnit;
class unit;

class cRegion{

	polygon2D shape;

	army a;


The class "army" is defined in unit.h which starts like this:

#pragma once

#include "main.h"
#include "world.h"
#include "cWalker.h"
#include "pathUnit.h"

So yes they both include each other. But how can I not do that? They both need to know how each other look since they use the members of each other (the classes "army" and "cRegion")

Edited by suliman

Share this post

Link to post
Share on other sites

You will need to refactor your dependencies so that there are no circular includes. Note that it's In C++ it's not possible for Class A to contain an instance of Class B, if Class B contains an instance of Class A. When you think about it, this would mean each one was of infinite size, because an A contains a B which contains an A which contains another B and so on. So, if army contains a cRegion and cRegion contains an army, it can never work.

You might fix this by having one object refer to the other via a pointer, smart pointer, or reference - these allow you to forward declare the class (as you have with army, armyunit, and unit already) and create a pointer to them without needing to #include their header file. (You will still need to #include it in your non-header files in order to work with those objects, however.)


Share this post

Link to post
Share on other sites

That is not the case, i misspoke (they do not include each other in that way)

I could rearrange some stuff and can now remove "include world.h" from unit.h

cRegion still complains that army is an undefined class even though the file (world.h) includes unit.h. How can I find where the error lies now?

Share this post

Link to post
Share on other sites

Well .... world.h has to include unit.h because army is actually included in cRegion (not just a pointer to it). First question, did you mean to do this or was this meant to be a pointer to army?  In any case I can't see the rest of the code but hopefully at most army (or some other class in unit.h)  only points to cRegion. You can do this, but you have to remove the  include to world.h and simply add a forward declaration of cRegion in unit.h (i.e. class cRegion;).  By doing this you can still have a pointer to cRegion in unit.h if you want. However you can't actually use any of it's members there, you can only pass the pointer around.  This is where the cpp file comes in. You want to put a any members in army that reference cRegion in unit.cpp, and you can put include "cRegion.h" at the top of it.  The down side is the compiler typically  can't inline those functions but it's probably not a big deal unless you are trying to squeeze every ounce of speed from your code.  Unfortunately C++ programmers have to deal with this all the time.

BTW you don't need the forward declaration of army in world.h or any forwards that you have include files for.  You typically only need to use them if you can't use an include, as I outlined above.

Share this post

Link to post
Share on other sites

Dependencies need to be a directed acyclic graph (ie. a tree with no circles).  This is true for classes and for header files.

Perhaps start by refactoring each class into its own header file, and then only include those header files you need where you need them.

If that fails to work because you have logical circular dependencies, try using members by reference (which confusingly usually means by pointer type as described above) instead of by value.

Share this post

Link to post
Share on other sites

shared_ptr can be used when the definition is not available in header space

an example solution:


#include <memory>

#pragma once

class B;

class A {

	std::shared_ptr<B> mB;



#include "a.h"

#pragma once

class B{

	A mA;


Edited by h8CplusplusGuru

Share this post

Link to post
Share on other sites

Thank you all for helping out!
I still dont get it to work. In unit.h I have no reference to stuff from world.h so i dont understand how it can be circular. Below are the full files (they are somewhat long but most of it is very simple members so quick to scroll through).



#pragma once

#include "unit.h"
#include "main.h"
#include "cWalker.h"
#include "pathMaster.h"

#include "player.h"

class army;
class armyUnit;
class unit;

class cRegion{

    polygon2D shape;

    army a;


class gameMap{

    bool startSave;

    char name[20];
    char tile[MAP_SIZE][MAP_SIZE];

    int2 startPos[MAX_PLAYERS];
    int2 size;

    cRegion region[REGION_MAX];
    bool endSave;



    bool withinMap(int x,int y){if(x>=0 && x<MAP_SIZE && y>=0 && y<MAP_SIZE) return true; return false; };

class gameObject{
    int type;
    int subType,team;
    float2 pos;
    float life,rot;
    float2 target;
    bool ranged;

    std::list<gameObject*>::iterator curIt;


class world

    hgeSprite * lightSprite;
    HTARGET lightTexture;
    HTEXTURE mapTexture;

    int attackSoundMass[30];
    int hitSoundMass[30];
    float2 pan;
    int2 sector;
    bool editorOn;

    float noUnitDelay;
    pathMaster pathSolver;

    std::list<gameObject *> objectList;
    std::list<army> armyList;
    std::list<unit> unitList;
    unit * selectedUnit;
    army * theNewArmy;

    gameMap map;
    HTEXTURE minimapTexture;
    hgeSprite * minimap;

    char roadBit[MAP_SIZE][MAP_SIZE];
    char tileVariation[MAP_SIZE][MAP_SIZE];
    float moveCost[10][30];

    // battle stuff
    char battleTerrain[BATTLE_X][BATTLE_Y];
    char battleTerrainCurrent[BATTLE_X][BATTLE_Y];
    army * bArmy1;
    army * bArmy2;
    bool battleOn;

    float aiWait;
    bool battleTurnLeft;

    bool startSave;

    float timeMatch,timeCurrentRound;
    int nextArmyId,nextTownId;

    int turnNumber;
    float gameTime;
    bool showUnitRange;
    int infoClass,infoType;
    char townBaseIncome[10];
    int gameScreen;

    bool explorationOn;
    int difficulty,baseIncome;
    int startingPoints;
    int gameMode;

    bool mapLoaded;

    int popupArmyID;
    int regionID;

    bool endSave;

    char goodsName[10][20];
    char incomeName[10][20];
    char regionRatingName[20][20];
    char unitClassName[10][20];

    void loadTextData();
    void loadFileData();

    void controlPan();
    void controlGame();
    void setupWorld();
    void drawWorld();
    void drawPanel();
    void doWorldTurn();

    void selectArmyFromMap();
    void createArmy(int team,int2 pos,int type,int level=0);
    void deleteArmy(army * u);
    void drawSystemInfo();

    //battle functions
    void setupBattle(army * a1, army * a2);
    void doBattle();

    void reset(){
        regionID = 0;
        battleOn = false;


        sprintf(goodsName[1],"Rare earth");


        sprintf(incomeName[4], "Drilling");
        sprintf(incomeName[6], "Rare earth");
        sprintf(incomeName[7], "Tech");

        for (int i = 0; i < 20; i++)
            regionRatingName[0] = 0;

        sprintf(regionRatingName[1], "Growth");
        sprintf(regionRatingName[2], "Mining");
        sprintf(regionRatingName[3], "Agriculture");
        sprintf(regionRatingName[4], "Drilling");
        sprintf(regionRatingName[6], "Rare earth");

        sprintf(regionRatingName[10], "Solar");
        sprintf(regionRatingName[11], "Biomass");
        sprintf(regionRatingName[12], "Hydro");
        sprintf(regionRatingName[13], "Geothermal");

        sprintf(unitClassName[0], "Soft");
        sprintf(unitClassName[4], "Mixed");
        sprintf(unitClassName[1], "Hard");
        sprintf(unitClassName[2], "Rotor");
        sprintf(unitClassName[3], "Plane");



    void editMap();
    bool loadMap(char * name);
    void saveMap(char * name);
    void setVisible(int2 pos,int range);
    void explore(int2 pos,int range);
    void updateMinimap(int2 pos,bool careAboutExplored=true);
    void drawMinimap(int2 pos,bool simple,int size);
    void effectMinimap( int type );
    void resetMap(int clearType=0);
    bool withinMap( int x,int y );
    void findNextUnit(int type=0);
    void setPan( float2 pos );
    void createObject( int type,int team,float2 pos,int data,float rot=0,float2 target=float2(-1,-1),bool ranged=false);
    std::list<gameObject *>::iterator deleteObject(gameObject * o);
    void updateObjects();
    void drawCost( int x,int y,short cost[10],int time=0,char * name=0,int nameGap=0,int workers=0,int background=0);
    void setMap( int x,int y,int type ,bool updateMini=true);
    void drawInfo();
    int getBuildingIcon(int bType);
    void drawSingleCost( int x,int y,float cost,int costType,char * name=0,int nameGap=0,int decimals=0,DWORD color=white, float secondValue=-1000,char * helpTextOverride=0, int endingStyle=0, bool forcePlus=false);
    int2 findFreeTile( int2 pos, int moveClass );
    void calcControl( int teamID, bool draw );
    void doArmyTurn(army * a);
    void setRoadBit( int x,int y );
    int10 getTerrainIncome( int x,int y,bool support=false, bool drawTiles=false );
    bool buildPosOk( int x,int y,bool support );
    void toggleInfo( int classIn, int typeIn );
    void setMapTiles(int2 singleTile=int2(-1,-1));
    void toggleGamescreen( int type);
    void drawGamescreen();
    float getSoundVol(int2 absPos,int team=0);
    void gainGoods(int team, int2 absPos,int type, int mass, int playSound=-1);
    int2 getBattlePos(float x, float y, bool leftSide);
    int getSeason();
    void newGame();
    army * getArmyFromId(int id);
    void doGame();
    int drawProgressBoxes(int x, int y, char * name, char * helpText, int value, int maxValue, int nameGap=90);
    void drawArmyUnit(int x, int y, armyUnit * u, int uType = 0);
    bool drawBuilding(int2 pos, int bType = 0, int damage = 0, char * helpText=0);
    void analyzeMap();
    void setPathSolver(bool battle);
    void drawBattle();
    bool withinMapCombat(int x, int y);
    bool enemyAdjacent(int2 pos, int team);
    unit * getUnit(int2 pos);



#pragma once

#include "main.h"
#include "player.h"
#include "cWalker.h"
#include "pathUnit.h"

class armyUnit{
    int type, xp, level;
    float hp;

        hp = 1;
    void draw( int x,int y,float scale,bool flipped =0, int bg =0, bool highLight=0);

class unit : public pathUnit, public armyUnit{

    float effectHit, effectAttack;
    bool leftTeam;
    int team;

    float2 projectilePos;
    float2 projectileGoal;
    float projectileRot;
    bool isAttacking;

        isAttacking = false;
        effectAttack = 0;
        effectHit = 0;

    void newTurn();
    void draw(int x, int y, float scale, bool flipped =0, int bg =0, bool highLight=0);
    void doAI();
    int2 findClosestFreeTile(int2 p);
    void endTurn();
    void attack(unit * victim);
    void doAttack();
    void hitUnit(unit * param1);

class cBuilding{
    short type, damage;


class army : public pathUnit{

    army * target;
    army * defendingThis;

    bool startSave; //--------------

    int type, xp, level;
    int stance;

    float winDelay;
    int winState;

    int2 rallyPoint;
    float dir;
    int radius;

    int2 offset;
    int team, commandedByLord, id;
    float morale, hp, flanking;

    armyUnit un[MAX_UNITS];

    float attackDelay,dmgPoints;
    int lastDamagedBy;
    int battlefield;

    float strength[5];
    short count[5];

    int2 lastExploredPos;

    int inBattleTime;

    int inBattle; //id of ongoing battle (if engaged in any)
    int2 placePos; //to place next unit in battle
    int samePlacePosTime;

    float effectAttack,effectHit;

    float armyUpkeep[2];

    //town (map settings
    char name[30];
    int regionRating[20]; // regional resources, power ratings etc

    float goods[10];
    int goodsIncome[10];
    int incomeFromField[10]; // mining, refineries etc
    int buildingIncome[4]; //direct income
    float incomeModifier[10];

    gameTrainingCue townCue[4]; // 0 construction 1 recruit 2 factories 3 dockyards
    bool coastal;

    float recruitsNow[50];
    int recruitsMax[50];

    int prodGenerated[4]; // how much is generated from factories and shipyards
    int prodPoints[4]; //for the cues: how much is done already

    //variable state
    int busyPop;
    float trade,wealth;
    float order,growth,corruption,pop;
    int maxWorkerPerField,maxBuilders,maxCarts;
    float trainingSpeed,musterSpeed;
    float upgradeProgress;
    float defense;
    int recoverMaxMen,defenseMaxMen;
    float growthBuildings, corruptionBuildings, orderBuildings;
    int limitedBuildings;

    int taxSetting,ruleSetting;

    cBuilding b[BUILDING_MAX];

    int takenBy;
    float takenDelay;

    bool endSave; //--------------

    pathUnit savedData;

        sprintf(name, "London");
        for (int i = 0; i < 4; i++){
            townCue.maxItems = 5;
            prodPoints = 0;
            prodGenerated = 1; // use fixed speed for all now
        //prodGenerated[0] = 1; //construction

        for (int i = 0; i < 4; i++)
            buildingIncome = 0;

        limitedBuildings = 0;
        orderBuildings = 0;
        growthBuildings = 0;
        corruptionBuildings = 0;

        battlefield=2; //open terrain

        for(int i=0;i<10;i++){

        for(int i=0;i<50;i++){

        for(int i=0;i<10;i++)





        for(int i=0;i<10;i++){


    void addUnit( int type,float mass=1 );
    int getValue();
    void doTownTurn( int draw=-1 );
    void drawAdd( int x, int y, int addType );
    bool armyAvailable( int type );
    bool buildingAvailable( int bType );
    void buildingEffect( int bType, bool added );
    int2 findWalkerGoal( int walkerType );
    bool hasBuilding(int bType);
    void draw(int x, int y, float scale, bool bg=true);
    void placeUnit(int unitID, int lane=-1, int intelligence=0);
    void nextPlacePos();
    float getTownData(int dataType, bool draw=false);
    void gtd(char * title,float mass=0, int decimals=0, bool multiply=false);
    float getPopFactor(int fType);
    void spawnUnit(short uType);
    void addBuilding(int bType,bool forceAllow, int removePos=-1);
    void gtd_(int c);
    void setTownDetails(bool updatePlayer=false);
    void takeTown(int style);
    void damageBuildings(int mass);
    void doExplore();
    void setArmyDetails();
    void removeFromCue(int cueId, int cueIndex);
    void addToCue(int addType, bool isBuilding);
    void setupTown();
    float getRecruitsAdded(int recruitsMax);
    bool unitAvailable(int i);
    float getDistanceFactor(int type);
    float getCityCountFactor(int type);
    int getGarrisonOrder();


Edited by suliman

Share this post

Link to post
Share on other sites
2 minutes ago, suliman said:

Thank you all for helping out!
I still dont get it to work. In unit.h I have no reference to stuff from world.h so i dont understand how it can be circular.

  Reveal hidden contents


  Reveal hidden contents



Basically, no matter what, you shouldn't have two files include each other. 

Share this post

Link to post
Share on other sites

Unless I'm missing something world.h includes unit.h and visa versa. This is what you showed I your first post.

Edited by Gnollrunner

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!