How does this C program compile and run with two main functions?

Quoting ld(1):

The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive.

When linking 2main, main symbol gets resolved before ld reaches -lstatic, because ld picks it up from prog.o.

When linking 1main, you do have undefined main by the time it gets to -lstatic, so it searches the archive for main.

This logic only applies to archives (static libraries), not regular objects.
When you link prog.o and static.o, all symbols from both objects are included unconditionally, so you get a duplicate definition error.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)