cgccreference

Undefined reference to main - collect2: ld returned 1 exit status


I'm trying to compile a program (called es3), but, when I write from terminal:

gcc es3.c -o es3

it appears this message:

/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status

What could I do?


Solution

  • It means that es3.c does not define a main function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.

    To compile only to an object file, use the -c option:

    gcc es3.c -c
    gcc es3.o main.c -o es3
    

    The above compiles es3.c to an object file, then compiles a file main.c that would contain the main function, and the linker merges es3.o and main.o into an executable called es3.