Jack M Jack M - 1 month ago 4x
C Question

Undefined reference to "main" in minimal C program

I'm trying to understand C compilation in a little more depth, and so I'm compiling and linking "manually". Here is my code

int main()
return 0;

And here is what I'm putting into my console (Windows):

gcc -S main.c
as main.s -o main.o
ld main.o

And when trying to link, I get:

main.o:main.c:(text+0x7): undefined reference to `__main'


You didn't link any of the necessary support libraries. C global objects like stdin, stdout, stderr don't just appear from nowhere. Command arguments and environment variables are pulled from the operating system. And on exit all those atexit() functions get called and the return code from main is passed to exit(return_code). Etc.

Check out the commands gcc -dumpspecs, gcc -print-libgcc-file-name. Look at all of the other libraries in that directory. You'll find a lot of those libraries and object files referenced in the output of dumpspecs. I don't know exactly when or how those spec rules are interpreted but you can probably get the idea. And I think the GCC info pages info gcc explain it in detail if you dig in far enough.

info gcc and then press 'g' and then enter 'Spec Files'

And as Jonathan Leffler said, the shortcut is to run gcc with the verbose option: gcc -v and just see what commands it used.