accessing data from other .cpp files

Started by
2 comments, last by Bregma 11 years, 6 months ago
I am working on a text-based RPG and I defined a vector in my game.cpp file and now I am trying to access it from my inputSystem.cpp file, it shows that it is unknown? I am wondering how I can access this vector from this other .cpp files?

-Thanks
Advertisement
See the extern keyword.
If your vector in game.cpp is

std::vector<someType> someName;

you should write in inputSystem.cpp

extern std::vector<someType> someName;
Better yet, put the extern declaration in a header, and include that header in both .cpp files. That way, if either the declaration (in the header) or the definition (in game.cpp) gets changed bit the other does not, you get a compile failure instead of a mysterious runtime failure.

Also, putting shared variable declarations in header files documents them as being shared between .cpp files.

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement