14.3 Linker error messages

file not recognized: File format not recognized

GCC uses the extension of a file, such as .c or .cc, to determine its content. If the extension is missing GCC cannot recognize the file type and will give this error.

Example:

#include <stdio.h>

int
main (void)
{
  printf ("Hello World!\n");
  return 0;
}

If the program above is saved in a file hello without any extension then compiling it will give the error:

$ gcc -Wall hello
hello: file not recognized: File format not 
recognized
collect2: ld returned 1 exit status

The solution is to rename the file to the correct extension, in this case hello.c.

undefined reference to `foo'
collect2: ld returned 1 exit status

This error occurs when a program uses a function or variable which is not defined in any of the object files or libraries supplied to the linker. It can be caused by a missing library or the use of an incorrect name. In the error message above, the program collect2 is part of the linker.

Example:

int foo(void);

int
main (void)
{
  foo();
  return 0;
}

If this program is compiled without linking to a library or object file containing the function foo() there will be an undefined reference error.

/usr/lib/crt1.o(.text+0x18): undefined reference to `main'

This error is a special case of the error above, when the missing function is main. In C and C++, every program must have a main function (where execution starts). When compiling an individual source file without a main function, use the option -c (see Creating object files from source files).