If you inplement a function in a separate .cpp file , how do you access objects instantiated in main from functions implemented that file?

Sometimes there is a need to spread code into several .cpp files to avoid clutter (for example main.cpp, other1.cpp, other 2.cpp) . So if you implement a function in a separate .cpp file, how do you access objects instantiated in main?

Solution: use extern

other1.cpp:

extern ObjectType objectname

void doSomething (void) 
{
      objectname.method();
}

Of course this is very basic stuff, but many new programmers ask about this so I included a short post about this here.

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *