user2073729
user2073729

Reputation: 1171

makefile which get also the name of the file compile

I need a makefile which get also the name of the file compile For example:

make foo

and the makefile should compile foo.c to foo. 

This is my makefile. How to change it?

all: out

out: out.o 
gcc -g  -m32 -Wall -o out out.o

out.o: out.c
gcc -m32 -g  -Wall -ansi -c -o out.o out.c


.PHONY: clean

#Clean the build directory
clean: 
rm -f *.o out

Upvotes: 0

Views: 125

Answers (2)

Beta
Beta

Reputation: 99084

Passing arguments directly to Make is trivially easy.

Your current makefile can be invoked with make foo, and will compile foo.c to produce foo, because Make has implicit rules for handling cases like foo.c => foo; there will be no error even though "foo" is not the target of any rule. (At least, this is the case with GNU Make 3.81, which is what I am using.)

If you want to control the choice of compiler and flags (as in your out rule), there is more than one way to do it. The simplest (though not strictly the best) is to modify a couple of variables in the makefile:

CC = gcc
CFLAGS = -g -m32 -Wall -ansi

Another option is to override the implicit rule with a pattern rule of your own:

%: %.c
    gcc -g -m32 -Wall -ansi -o $@ $<

If you want it to build foo.o in a separate step, you must split the rule into two rule-- and also put in a rule with no recipe to cancel Make's implicit rule:

%: %.o
    gcc -g -m32 -Wall -o $@ $^

%.o: %.c
    gcc -m32 -g  -Wall -ansi -c -o $@ $<

%: %.c

Further refinements are possible, once you have mastered the basics.

Upvotes: 1

Sagar Sakre
Sagar Sakre

Reputation: 2426

There is no direct way where you can pass arguments to the Makefile but instead you can take advantage of variables to achieve what you want. Check the modifications done to the Makefile below

NAME ?=out #Default binary generated is out if you dont pass any argument

${NAME}: ${NAME}.o

gcc -g  -m32 -Wall -o ${NAME} ${NAME}.o

${NAME}.o: ${NAME}.c

gcc -m32 -g  -Wall -ansi -c -o ${NAME}.o out.c

.PHONY: clean

#Clean the build directory

clean:

`rm -f *.o ${NAME}`

And you should call the Makefile by typing

$ make NAME=foo

$ make clean NAME=foo

Upvotes: 1

Related Questions