Colin Fausnaught
Colin Fausnaught

Reputation: 323

Simple compiling using a Makefile?

I'm having some trouble grasping the concept of a Makefile. I'm coding a project in C and I have two .c files that need to be compiled together in order to run the program. I went over some of the concepts with some other people but am still having trouble grasping the concept of Makefiles. This is what I have.

Makefile:

hs.c:
        gcc -o hs hs_util.c hs.c

hs.c is dependent on hs_util.c's functions in order to accomplish tasks. I know this because the header file from hs_util is included...

in hs.c:

#include "hs_util.h"
#include "hs_config.h"

in hs_util.c

#include "hs_config.h"
#include "hs_util.h"

when I run the "make" command, it says "make: 'hs.c' is up to date." which is great, but the hs file isn't being created. What am I doing wrong?

Upvotes: 2

Views: 130

Answers (2)

tipaye
tipaye

Reputation: 474

I think you have a little typo. Your makefile wants to build a target "hs.c"

Try changing the following:

> hs.c:
>         gcc -o hs hs_util.c hs.c

To

hs:
        gcc -o hs hs_util.c hs.c

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 81052

You told it to build hs.c not hs. So it tried but that existed and you didn't tell it any other files that would force it to think the file was out of date (which is good because you don't want that).

You want:

hs:
        gcc -o hs hs_util.c hs.c

but that's not enough either. That will only build once and then stop (you'll need to delete hs before it will build again).

You need to teach make about what input files go in to making the target (hs).

hs: hs_util.c hs.c
        gcc -o hs hs_util.c hs.c

Having done that you can use automatic variables to avoid duplicating yourself.

hs: hs_util.c hs.c
        gcc -o $@ $^

Having done that you can actually take advantage of the make built-in rules and just do this.

hs: hs_util.o hs.o

If you want to also tell make that it needs to rebuild the .o files when the .h files change you can add this.

hs.o hs_util.o: hs_util.h hs_config.h

Remember that the general form for a make rule is (example, syntax):

output-file: input-file
    commands to generate output-file from input-file

Upvotes: 3

Related Questions