[prog] error: "reference 'main' can not be resolved"
Almut Behrens
almut-behrens at gmx.net
Wed Nov 9 20:04:59 EST 2005
On Wed, Nov 09, 2005 at 09:56:58AM +0200, Asl? wrote:
> hi,
> i suspected that the message was because the linker could not find a
> "main" within the source codes. and then i just tried commenting out
> the whole main block, and then building the project. Microsoft Visual
> C++ .NET (i know it's a shame talking about using .NET in a linux
> mailing list) The compilation stage was completed without and error,
> but then in the linking stage the i got this message:
> "unresolved external symbol _main referenced in function _mainCRTStartup"
>
> that has the same meaning with the pseudo error message i was talking about.
>
> So, as to conclude, it was a linker related error..
Exactly, it's the linker.
You'd typically get a similar error message from gcc, when you try to
compile some C source which is part of a larger program, but forget to
supply the -c switch (compile only) on the commandline, e.g.
$ gcc some_program_fragment.c
/usr/lib/crt1.o: In function `_start':
/usr/lib/crt1.o(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status
^^
Without the -c, the compiler defaults to a full compile-and-link cycle
(i.e. it tries to generate an executable program). And, as you know,
every C program needs a main() function as its "entry point" (where
execution begins). So, if there is no main() in any of the program
fragments you're trying to compile/link, the linker will complain...
Actually, the symbol main is used as an external reference in the
standard startup code (here crt1.o), which is eventually supposed to
transfer execution to the actual program:
$ nm /usr/lib/crt1.o
00000004 R _IO_stdin_used
00000000 D __data_start
U __libc_csu_fini
U __libc_csu_init
U __libc_start_main
00000000 R _fp_hw
00000000 T _start
00000000 W data_start
U main
As you can see, the symbol main is flagged 'U' (undefined), which means
it has to be implemented somewhere else (i.e. by your program), to
allow the linker to resolve that reference. If you do an 'nm' on the
object file where main is implemented, you'd see a 'T' next to it (T
means code, aka 'text' section -- ...to make things less obvious for
the uninitiated :)
By default, that startup code is linked (with the rest of what you
specify) during every run of gcc, unless you specify -c (or -E, -S,
-nostartfiles, -nostdlib for that matter). And, as already said above,
the linker will complain if any symbol remains undefined...
Hope that helps somewhat...
Almut
More information about the Programming
mailing list