darylnak
darylnak

Reputation: 239

How to fix Makefile error?

I have created a Makefile. Right now, I get these errors:

Here is the Makefile:

brians_brain_cellular_automata: brians_brain_cellular_automata.o brians_brain.o cell.o cell_grid.o
    gcc -Wall brians_brain_cellular_automata.o brians_brain.o cell.o cell_grid.o

brians_brain_cellular_automata.o: brians_brain_cellular_automata.c brians_brain.o cell.o cell_grid.o
    gcc -Wall -c brians_brain_cellular_automata.c brians_brain.o cell.o cell_grid.o

brians_brain.o: brians_brain.c cell_grid.o cell.o list.o
    gcc -Wall -c brians_brain.c cell_grid.o cell.o list.o

cell_grid.o: cell_grid.c cell.o
    gcc -Wall -c cell_grid.c cell.o

cell.o: cell.c
    gcc -Wall -c cell.c

list.o: list.c cell.o
    gcc -Wall -c list.c cell.o

Assume tabs are properly used.

What confuses me the most is this Makefile worked earlier today. I was typing some code in one of the dependencies and it started doing this. I reverted those changes but I still get these errors. What am I doing wrong?

Upvotes: 0

Views: 3749

Answers (1)

dbush
dbush

Reputation: 223689

When compiling an object file, you only need to pass in source files, not other object files. The objects files are used when linking in the executable. That's the source of the warnings.

As for the error, you're not including list.o when linking the executable, nor is it listed as a dependency. So you're getting "undefined reference" errors for functions in that file.

So your makefile should look like this:

brians_brain_cellular_automata: brians_brain_cellular_automata.o brians_brain.o cell.o cell_grid.o list.o
    gcc -Wall brians_brain_cellular_automata.o brians_brain.o cell.o cell_grid.o list.o

brians_brain_cellular_automata.o: brians_brain_cellular_automata.c 
    gcc -Wall -c brians_brain_cellular_automata.c

brians_brain.o: brians_brain.c
    gcc -Wall -c brians_brain.c

cell_grid.o: cell_grid.c
    gcc -Wall -c cell_grid.c

cell.o: cell.c
    gcc -Wall -c cell.c

list.o: list.c
    gcc -Wall -c list.c

Since each object file is built the same way, you can actually define a rule using wildcards to compile an object file:

brians_brain_cellular_automata: brians_brain_cellular_automata.o brians_brain.o cell.o cell_grid.o list.o
    gcc -Wall brians_brain_cellular_automata.o brians_brain.o cell.o cell_grid.o list.o

%.o: %.c
    gcc -Wall -c $<

With this rule, each object file referenced in the brians_brain_cellular_automata target will be built with this rule.

Upvotes: 2

Related Questions