Januan
Januan

Reputation: 67

How to properly create and use makefile

I'm getting started with makefiles and I'm having some problems.

I have one file which is fase_1.c that I want to compile and run.

I'm trying to make a simple makefile where I make and make clean. This is what I tried:

OBJECTS = fase_1.o
CFLAGS = -Wall
NAME = makefile

build: $(OBJECTS)
    cc $(CFLAGS) $(OBJECTS) -o $(NAME)

clean: 
    rm -f *.o
    rm -f $(NAME)   

I do make, and it creates fase_1.o and makefile. Then I run ./makefile (is there another way to do it without like make or make clean but to run it?). Then I type make clean, and it says that there's a missing separator and that the line is ignored and doesn't remove fase_1.o and makefile (what I want to do). Am I separating the lines right? Maybe it has something to do with tab or my editing but I can't find where.

Upvotes: 3

Views: 78

Answers (2)

blippy
blippy

Reputation: 1540

Here's a rewrite. Call it Makefile, though, not makefile:

OBJECTS = fase_1.o
CFLAGS = -Wall
NAME = fase

$(NAME): $(OBJECTS)
    cc $(CFLAGS) $(OBJECTS) -o $(NAME)

run : $(NAME)
    ./fase

.PHONY: clean
clean: 
    rm -f *.o
    rm -f $(NAME)   

There are fancier improvements that could be made, but it's probably best not to get bogged down at this stage. As a bonus, I have added .PHONY. This tells make that the target clean is a phony target; it doesn't actually create anything called clean.

You don't have to make run dependent on $(NAME), of course, but it makes sense in this particular context.

Upvotes: 3

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21502

It looks like you are using GNU make. From the info page:

By default, when 'make' looks for the makefile, it tries the following names, in order: 'GNUmakefile', 'makefile' and 'Makefile'.

Your executable is called makefile. When you run make, it tries to parse the executable as Makefile. Either rename the executable, or specify the makefile explicitly:

make -f Makefile clean

Upvotes: 2

Related Questions