Today, while working with one custom library, I found a strange behavior.
A static library code contained a debug main()
function. It wasn\'t inside a #define
When you link a static library (.a), the linker only searches the archive if there were any undefined symbols tracked so far. Otherwise, it doesn't look at the archive at all. So your 2main
case, it never looks at the archive as it doesn't have any undefined symbols for making the translation unit.
If you include a simple function in static.c
:
#include
void fun()
{
printf("This is fun\n");
}
int main()
{
printf("Main in static.c\n");
}
and call it from prog.c
, then linker will be forced to look at the archive to find the symbol fun
and you'll get the same multiple main definition error as linker would find the duplicate symbol main
now.
When you directly compile the object files(as in gcc a.o b.o
), the linker doesn't have any role here and all the symbols are included to make a single binary and obviously duplicate symbols are there.
The bottom line is that linker looks at the archive only if there are missing symbols. Otherwise, it's as good as not linking with any libraries.