Simone Serra
Simone Serra

Reputation: 301

C: How to compile an header included in another header with makefile?

sorry for my bad english first of all...

Here's my problem: I have my application composed by main.c (main program), functions.c (code), functions.h (prototypes) and headers.h (typedefs, defines, etc).

In the main's code (and in functions.c, of course) I'm including functions.h, while in functions.h I'm including headers.h.

How should i compile headers.h in a makefile? I don't have headers.c: do I need to create headers.o anyway?

Here's my makefile's code:

application: main.o functions.o
  gcc -o application main.o functions.o

main.o: main.c functions.o
  gcc -c -Wall -pedantic main.c

functions.o: functions.c functions.h
  gcc -c -Wall -pedantic functions.c

clean: 
  rm -f *.o

Everything works fine if i manually compile headers.h with

gcc -c -Wall -pedantic headers.h

EDIT: this is no longer true. I don't know why 5 minutes ago it works.

getting a .gch file. Where am I supposed to write that line in the makefile?

Thank you!

Upvotes: 2

Views: 811

Answers (4)

rsz
rsz

Reputation: 177

You don't have to compile headers. You can do :

SRCS =  ./main.c \
        ./function.c \

OBJS = $(SRCS:.c=.o)

all: application

application:    $(OBJS)
                gcc -Wall -pedantic $(OBJS) -I./ -o output_name

clean:
                rm -f $(OBJS)

and then : make all

Upvotes: 2

In addition to other answers....

[I'm] getting a .gch file. Where am I supposed to write that line in the makefile?

.gch extensions is for GCC pre-compiled headers. This is not a feature for newbies, and it is not a feature useful for small (less than half a million source lines) software projects. See this answer for more about pre-compiled headers, which you probably don't need.

Hence, after fixing your Makefile and committing your source code to your version control system (if you don't use one, use now git before doing anything else!), you could rm -vif *.gch

Upvotes: 1

mikedu95
mikedu95

Reputation: 1736

You don't compile a header. Rather, you can do:

main.o: main.c headers.h
  gcc -c -Wall -pedantic main.c

functions.o: functions.c functions.h headers.h
  gcc -c -Wall -pedantic functions.c

Upvotes: 4

2501
2501

Reputation: 25752

Just add the header right here:

                                         v
functions.o: functions.c functions.h headers.h
  gcc -c -Wall -pedantic functions.c

And add headers in main. You can remove functions.o, unless you want main.o to depend on functions.o:

main.o: main.c functions.h headers.h
  gcc -c -Wall -pedantic main.c

You do not need to create headers.o, you should not compile headers.

Upvotes: 2

Related Questions