lulyon
lulyon

Reputation: 7265

makefile give error undefined reference to 'main'

Makefile:

all: a.out

a.out: b.o a.o 
    gcc -o b.o a.o

a.o: a.c 
    gcc -c a.c

b.o: b.c 
    gcc -c b.c

.PHONY:clean

clean:
    rm *.o a.out

with make, give information:

error: undefined reference to 'main'

collect2: ld return 1

make: * [a.out] error 1

But when put source file a.c and b.c into Eclipse CDT, it compiles well. Please explain what is wrong with my makefile?

PS: a.c:

int global_1 = 100;

b.c:

extern int global_1;

int main()
{
    int global_2 = global_1 * 2;
    return 0;
}

Upvotes: 0

Views: 5322

Answers (2)

Jens
Jens

Reputation: 72746

This rule doesn't specify the correct result file:

a.out: b.o a.o 
    gcc -o b.o a.o

It should be

a.out: b.o a.o 
    gcc -o "$@" b.o a.o

That's what you get for violating one of Paul's Rules of Makefiles. BTW, it's not the makefile that "gives the error", it's the compilation, specifically the linker.

Upvotes: 1

unwind
unwind

Reputation: 400089

This:

a.out: b.o a.o 
    gcc -o b.o a.o
        \----/
           |
           |
     this says "name
     the output b.o"

is overwriting the b.o object file with the output file. I'm pretty sure make is clever enough to figure the required command out without any input, so try deleting the second line.

Upvotes: 0

Related Questions