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'
To fix this error, correct the spelling of the main() function.
Undefined reference to main could mean that you haven't defined one of the functions in your class or something of that nature.
This error is often generated because you have typed the name of a function or variable incorrectly. For example, the following code: #include <stdio.h> void print_hello() { printf ("Hello!\n"); } /* To shorten example, not using argp */ int main() { Print_hello(); return 0; }
Every C program has a primary function that must be named main . The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With