Copyrighting code as coauthored. Devide work before starting?

Do I understand correctly that in order to copyright a co-authored work, the co-authors must in advance, of starting on the coding, have made a written agreement stating which part of it each is to do? If so, is that line by line or what?

No, copyright law requires no such advance agreement. Here’s what it actually says about works with multiple authors:

A lot of joint ownership of copyright really depends upon the co-authors’ intent. Here is a good overview of joint copyright: Like a lot of copyright issues, disagreements that result from joint ownership of copyright most often take a judge to decide. Your best hedge against problems is to be sure you have things spelled out specifically in a signed agreement that you and your co-author establish.

@Dan_Grossman ; The link you left appears to be about collective works which is different than a single piece authored by more than one person.

I linked to the section about single works with multiple authors, not the section about collective works. This is the US Copyright Office website.

A joint work is defined in the copyright law as a “work prepared by two or more authors with the intention that their contributions be merged into inseparable or interdependent parts of a unitary whole.” In a joint work, all authors own an undivided interest in the entire work, without the need for any transfer of rights.

For some reason when I click your link it resolves to: Registration of a Single Work Containing Multiple Authorship Elements by Different Authors