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

后端 未结 3 1513
一个人的身影
一个人的身影 2021-01-30 19:38

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

3条回答
  •  走了就别回头了
    2021-01-30 20:33

    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.

提交回复
热议问题