[c] C Linking Error: undefined reference to 'main'

I have read the other answers on this topic, and unfortunately they have not helped me. I am attempting to link several c programs together, and I am getting an error in response:

$ gcc -o runexp.o scd.o data_proc.o -lm -fopenmp
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
make: * [runexp] Error 1

I have exactly one main function and it is in runexp. The form is

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

Any thoughts on why I might get this error? Thanks!

This question is related to c linker

The answer is


You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.


You're not including the C file that contains main() when compiling, so the linker isn't seeing it.

You need to add it:

$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp

Generally you compile most .c files in the following way:

gcc foo.c -o foo. It might vary depending on what #includes you used or if you have any external .h files. Generally, when you have a C file, it looks somewhat like the following:

#include <stdio.h>
    /* any other includes, prototypes, struct delcarations... */
    int main(){
    */ code */
}

When I get an 'undefined reference to main', it usually means that I have a .c file that does not have int main() in the file. If you first learned java, this is an understandable manner of confusion since in Java, your code usually looks like the following:

//any import statements you have
public class Foo{
    int main(){}
 }

I would advise looking to see if you have int main() at the top.