How are squawk codes assigned?
To start out with, I'll be referring to how the US does it, and it's generally laid out in the National Beacon Code Allocation Plan. Every facility has various blocks of codes that they can use to assign to flight plans, as described in the linked document. For example, a smaller tower/approach control, could use the codes 0101-0177 for IFR flights that are only in their airspace, and 0201-0277 for the VFR flights that stay in their airspace, and a Center would have a similar bank of codes for flights just in their airspace, and then a different bank for codes that go to different centers. The whole purpose to these allocations, is to minimize the need to change the squawk code while in the air, and to avoid overlap with adjacent facilities. 

As flight plans are submitted to the various computers, about 30 min before an Instrument flight plan's proposed time, it's officially assigned a code from the available blocks, and it's printed at the departure airport or facility that'll first work it. Flight plans stay in the system, depending on however long the center sets. Often it's 2 hours, sometimes 3, but during bad whether when lots of flights are being delayed, it could be extended to 4+ hours. The drop interval helps to keep enough codes available for aircraft intending to depart, while allowing flight plans to go away if something happens and the flight won't be departing.

If the aircraft just randomly calls ATC, the controller types it in to either the radar or flight plan system, depending on what extent the pilot wants services, and then the system prints out an appropriate beacon code.