Sometimes the government entity building a road over or under a rail line had to pay the cost. Other places had laws in which the railroad was required to chip in. I'm an employee of a railroad. On another railroad related forum, I have gotten to know a guy who used to be a civil engineer for my company. Here in New York State, the state has totally paid for some projects. One was to grade separate from city streets in Albany, and also weave among the new (at the time) interstate in the downtown area. The state also paid for a couple of realignment projects around the Village of Ballston Spa, and the City of Saratoga Springs.
The previous poster mentioned the telegraph pole lines along the tracks. In later years they were sometimes converted to telephone. Other times the poles had lines to power and control the signal system. Where centralized traffic control is used, the lines send code. The system worked, as I understand similar to old dial telephones. Certain pulses would tcommand switches to throw, and signal indications to be displayed. The signal would send code back, which told the command station that the command had been acted upon. Certain lines had separate pole lines for signal, and others for communication. Now much of the signal data is sent via radio, dedicated telephone lines, and often fiber optic lines. The railroad sometimes gets free use, in exchange for the telephone company getting to lay their lines along the right of way.