It is not a sipmple aswer to this question:
Most towers have a small "bank" of codes available for use in their airspace, or in a area not to far away. Additionally each Approach or Area Centre have a bank for flights in their area, if the area is large, some codes may not be permittet used in certain areas.
IFR flights generally keep their code trough out their flight, and it's picked from the Area code bank, but it the flight is long, a change of code might be in order. (Ex: the plane get a new code when crossing a certain FIR border or whatever)
The use of the code "banks" are a bit different from place to place.
Certain parts of the allotted bank might be for the specific FIR only, while another part of the bank is permitted used outside the FIR.
If I have a flight that depart my airfield for a short IFR or VFR flight to one of 4 neighbouring airports I can assign a squawk from our local bank.
If I have a flight departing to ENGM, wich is outside the scope of our codebank, I get a squawk from the Bodo Controll Centre.
They pick a squawk from a "outside FIR, inside country" code bank.
If the flight has ESSA as destination (not in FIR or country), they pic a code from a different bank.
That said, the code bank might be in a computersystem, or just a list on a pice of paper.
Our system will get a upgrade this spring, and ALL
squawks for Norway will be assigned from a automatic central code bank, picking codes according to flight plan route.