Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to "main" in minimal C program

Tags:

c

gcc

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'
like image 544
Jack M Avatar asked Aug 24 '16 23:08

Jack M


People also ask

How do you fix undefined references to Main in C?

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

What is an undefined reference to main?

Undefined reference to main could mean that you haven't defined one of the functions in your class or something of that nature.

What is undefined reference to printf in C?

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; }

What is the main function in C?

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.


1 Answers

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.

like image 130
Zan Lynx Avatar answered Oct 08 '22 12:10

Zan Lynx