Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

reference

gcc

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?

like image 418
noobsharp Avatar asked Nov 01 '11 10:11

noobsharp


People also ask

What is mean by ld returned 1 exit status?

The ld returned 1 exit status error is the consequence of your previous errors as in your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors.

How do you fix undefined references to Main?

To fix this error, correct the spelling of the main() function.

How do I fix undefined reference error in C ++?

So when we try to assign it a value in the main function, the linker doesn't find the symbol and may result in an “unresolved external symbol” or “undefined reference”. The way to fix this error is to explicitly scope the variable using '::' outside the main before using it.


2 Answers

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.

like image 105
Blagovest Buyukliev Avatar answered Sep 18 '22 09:09

Blagovest Buyukliev


Perhaps your main function has been commented out because of e.g. preprocessing. To learn what preprocessing is doing, try gcc -C -E es3.c > es3.i then look with an editor into the generated file es3.i (and search main inside it).

First, you should always (since you are a newbie) compile with

  gcc -Wall -g -c es3.c   gcc -Wall -g es3.o -o es3 

The -Wall flag is extremely important, and you should always use it. It tells the compiler to give you (almost) all warnings. And you should always listen to the warnings, i.e. correct your source code file es3.C till you got no more warnings.

The -g flag is important also, because it asks gcc to put debugging information in the object file and the executable. Then you are able to use a debugger (like gdb) to debug your program.

To get the list of symbols in an object file or an executable, you can use nm.

Of course, I'm assuming you use a GNU/Linux system (and I invite you to use GNU/Linux if you don't use it already).

like image 38
Basile Starynkevitch Avatar answered Sep 18 '22 09:09

Basile Starynkevitch