Home > Software design >  Access class from another C file
Access class from another C file

Time:09-17

So I have a "main.cpp" file which I have declared an object of my class player:

main.cpp:

#include "player.h"

Player player;

int main() {
  //
  player.update();
}

I would like to access this object from multiple different C files. However, I would like to do this without using the keyword extern as i'm trying to stay away from global variables.

Hope someone can help me with this. Thanks in advance!

CodePudding user response:

Rather than write functions like

file1.cpp

#include "player.h"

extern Player player;

void doStuffToPlayer() {
    player.update();
}

file2.cpp

#include "player.h"
#include "file1.h"

Player player;

int main() {
    doStuffToPlayer();
}

You can instead write

file1.cpp

#include "player.h"

void doStuffToPlayer(Player & player) {
    player.update();
}

file2.cpp

#include "player.h"
#include "file1.h"

int main() {
    Player player;
    doStuffToPlayer(player);
}

CodePudding user response:

Ok, so after some more research, I have found that I can access objects from other C files using getters.

main.cpp:

#include "objects.h"

int main()
{
  getPlayer().update();
}

objects.cpp:

  Player player;
  
  Player& getPlayer()
  {
    return player;
  }

Hope this helps someone in the future!

  • Related