I've been making a project that requires different files to have access to objects declared in other files such that circular dependencies are created. I've done some research and discovered that pointers and forward declarations should be able to fix this, but I'm a little hazy on how this is done.
Example:
File 1 declares variable x, must edit x and y
File 2 must edit x and y, declares variable y
I know this isn't the best example, as you could probably declare x and y in the same file, but please suffice it to say that I'm unable to do that in my project. Thanks in advance for any help, and I'll be happy to provide code snippets if necessary.
Thanks, but for your first example of externs, would 1.cpp and 2.cpp have to include each other? If not, how is it that the files can see the variables? Also, the variables I'm working with are objects, which I should've mentioned earlier, so the file that creates the objects needs access to the class.
No, cpp files should never include each other. They only need to include the header. The files can see the variables because their declarations are visible - same as for extern. The linker will later figure out what object goes to what file.
Nothing changes if you use types of your own. C++ tries hard to treat all types equally, whether they are int or some struct Foobar.
The types referenced are, of course, validly defined in other headers and .cpp files. Additionally, I'm getting a lot of these errors repeated, as if the include guards aren't working. Any advice?
#include "ObjectList.cpp"
class Player
{
// . . . .
};
Player.cpp:
1 2
#include"Player.h"
//Blah blah blah, functions try to use the "player" object but can't.
I get errors such as:
error C2146: syntax error : missing ';' before identifier 'player'
error C2228: left of '.<name of function belonging to player>' must have class/struct/union
There are identical issues in the other headers referenced by ObjectList.cpp
//object_list.h
#pragma once
#include "player.h"
extern Player player; //as we want to declare an instance, we need to include its class definition
//player.h
#pragma once
class Player{
//...
};
//main.cpp
#include "object_list.h" //if you intend to use the `player' object
//somewhere_over_the_rainbow.cpp
#include "player.h"
Player player; //instantiating the player