4

I'm writing a little implementation of Conway's Game of Life in C. The source code is split in three files: main.c and functions.c/functions.h, where I put my functions definitions and declarations.

Now, to create a grid of cell, I have a matrix of this type:

Cell grid[GRID_HEIGHT][GRID_WIDTH];

where GRID_HEIGHT and GRID_WIDTH are constants defined in functions.h:

#define GRID_HEIGHT 10
#define GRID_WIDTH 10

The program runs fine, compiled with make and Makefile. But the problem is: if I try to change GRID_HEIGHT or GRID_WIDTH, when I run again my Makefile it says that all files are up-to-date! I've tried to compile using the good ol' way gcc main.c etc. and it runs as it should. So, why make does not recompile the source?

This is my Makefile:

CC = gcc
OBJECTS = main.o functions.o

Game\ of\ Life : $(OBJECTS)
    $(CC) $(OBJECTS) -o Game\ of\ Life -lncurses

%.o : %.c
    $(CC) -c $< 
Lubulos
  • 290
  • 2
  • 9
  • Because `main.o` depends on `functions.h` but you didn't indicate that dependency in the makefile – pmg Dec 24 '11 at 19:39
  • If this all seems too complicated, I might recommend [SCons](http://scons.org) - your complete build file would be the single line `Program("Game Of Life", ["main.c", "functions.c"], LIBS=["ncurses"])` SCons automatically determines header file dependencies depending on the sources themselves, so you don't have to think about it. – Greg Hewgill Dec 24 '11 at 20:02

3 Answers3

7

Because you haven't told it that recompilation depends on functions.h.

Try adding this to your Makefile:

%.o : functions.h

Alternatively, modify your existing rule to be:

%.o : %.c functions.h
    $(CC) -c $< -o $@
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

You've told make that .o files don't depend on .h files, so it doesn't recompile anything when a header changes.

Getting it to work right is hard (you need to generate dependencies for each .c file), but an easy way is just to define HEADERS which contains all your header files and make each .o file depend on all your headers.

3

If you're using GCC (well, you are), then it can be solved generically by passing -MD option to the compiler, GCC will generate a file containing Make dependencies on included headers:

CC = gcc
OBJECTS = main.o functions.o

%.o : %.c
    $(CC) -MD -c $<

-include $(OBJECTS:.o=.d)

Some headers-related information can also be found in this question.

Community
  • 1
  • 1
Eldar Abusalimov
  • 24,387
  • 4
  • 67
  • 71