In the beginning railway models were made to no particular scale.
When electrical motors became available the first motorized models were made. As the early motors were large, the early models were large.
In around 1892 Marklin created the numbered gauges (#4, #3, #2. #1) and #0 which became O Gauge.
Early motors ran on A/C, in a few short lived early models 'House Voltage!'. This was quickly reduced to a lower safer voltage. This led to the three rail system still used by Lionel, Marklin and others.
Advances in DC motor design (smaller and more powerful) and reductions in house sizes led to a new scale "Half-O" or HO. In England and other places this was Double-O "OO".
Smaller scales TT, N, then Z came along as motors became smaller and manufacturing processes improved.
For a more in depth look at the history of model trains we recommend the book "150 Years of Train Models" from Carstens Publications.