tags:

views:

247

answers:

1

Support you have a C program included by some files, and some one is consisted by some others, so as follows:

----------------------------------------
File            | Included files           
----------------------------------------
main.c          | stdio.h, table.h
----------------------------------------
list.c          | list.h
----------------------------------------
symbol.c        | symbol.h
----------------------------------------
table.c         | table.h
----------------------------------------
table.h         | symbol.h, list.h
----------------------------------------

please help me to create a makefile, thank you very much! This is my Makefile, but there is a problem? who can debug these problems, thanks!

hello:  main.o table.o 
    gcc main.o table.o -o hello

main.o: main.c table.h
    gcc -c main.c

table.o:    table.c table.h
    gcc -c table.c

symbol.o:   symbol.c symbol.h
    gcc -c symbol.c

list.o: list.c list.h
    gcc -c list.c


clean:
    rm hello *.o
+6  A: 

Here's a start, not exactly how a professional would do it, but good for a beginner level:

hello: main.o list.o symbol.o table.o
    gcc -o hello main.o list.o symbol.o table.o

main.o: main.c table.h symbol.h list.h
    gcc -c -o main.o main.c

list.o: list.c list.h
    gcc -c -o list.o list.c

symbol.o: symbol.c symbol.h
    gcc -c -o symbol.o symbol.c

table.o: table.c table.h symbol.h list.h
    gcc -c -o table.o table.c

clean:
    rm hello *.o

The specific problem with your given makefile is that you're not linking in all the object files. Because main.c includes table.h and table.h includes symbol.h and list.h, your program will almost certainly need to link symbol.o and list.o as well.

It's also good practice to follow header dependencies (e.g., main.o depends on table.h and symbol.h/list.h because table.h depends on those two) - this is because there's no "neat" way to get an intermediate file for header dependencies.

And you rarely put standard headers into make files simply because they're not expected to change - if they do (new compiler), just clean and make fresh.

paxdiablo
+1, a very good example for a beginner, including header dependencies. I have never been able to get them 'just right' using gcc -M. Close, but never perfect.
Tim Post