The trick is the following: Just make use of WordPress' rich amount of hooks, filters and actions. That way, WordPress will (mostly) know what to do and sort things for you.
That may not be a satisfying answer in the first place or in terms of $GLOBALS.
However in general, the first thing to understand is the following:
Functions in a theme always go into the functions.php. This file is always loaded and will be the first place to start when building a theme and adding functionality to it. This file will contain all your code that manipulates the output and the things you want to do in the backend.
There, to add your own stuff all you need to do is to use one of the hooks, filters and/or actions.
See this link in the codex.
Same goes for a plugin. In case you want to add functionality not in a theme, but reusable - put it in a plugin. The basic setup may be tricky to understand, but once you get the hang of it, it's really cool.
You can also declare classes in your functions.php and call them somewhere in your theme.
When building a plugin you need to follow the coding standards to make WordPress "see" your code.
Download, install and activate Hookr, visit your frontend. It will show all available "Hooks" where you can check in to inject your code.