1

I read about recursive variable in makefiles. Because we put '=' in the following code, it's a recursive variable, as apposed to ':='

CC = gcc -Wall
# we want to add something to the end of the variable
CC = $(CC) -g
hello.o: hello.c hello_api .h
$(CC) -c hello.c -o hello.o

I didn't understand still, why in this case we have an infinent loop.

user1047069
  • 935
  • 2
  • 13
  • 25
  • 2
    This does not look like a valid Makefile to me. First of all, the invocation of the $(CC) command should be preceded by a character. Also, seems like `hello_api` and `.h` should not be separated. – SirDarius Dec 01 '13 at 11:15

3 Answers3

8

From the manual:

The first flavor of variable is a recursively expanded variable. [...] The value you specify is installed verbatim; if it contains references to other variables, these references are expanded whenever this variable is substituted (in the course of expanding some other string). When this happens, it is called recursive expansion.

Your CC variable is of this flavour. It's content is literally $(CC) -g; it is not gcc -Wall -g. So when you expand this variable, you first expand $(CC), which again contains the reference to itself, and so you have infinite recursion.

The difference when using := is that the right-hand-side is evaluated immediately and the result is assigned to the variable.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

Use CC += -g in the 5th line

More information here http://www.gnu.org/software/make/manual/make.html#Flavors

weisert
  • 185
  • 5
-1

Your Makefile is wrong; should be (assuming a GNU make)

 RM= rm -vf
 CC= gcc
 CFLAGS= -Wall -g
 .PHONY: all clean
 all: hello
 hello: hello.o
 hello.o: hello.c hello_api.h
 clean:
       $(RM) *.o *~

Last line, just after clean:, starts with a tab character

See also this answer for more. Run make -p to understand the implicit rules useful in the above case.

Read carefully the documentation on make variables. Those defined with = are expanded lazily and textually (with the make variables further expanded in the substituted text). In other words, CC= $(CC) -g gives an infinite loop. Because the first $(CC) is replaced with $(CC) -g which is rescanned and its $(CC) is replaced with the same (getting $(CC) -g -g) etc etc ad infinitum.

make is mostly a string processing utility (with of course the dependency thing based upon file modification time). It does not really have some proper AST as internal representation of the commands to be run.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • thanks. but still, Im asking about infinite loop that can take place in a makefile due to recursive variables. Can u give a simple example and explain ? – user1047069 Dec 01 '13 at 11:19
  • Explanation given in [Kerrek's answer](http://stackoverflow.com/a/20311543/841108); but I also gave a bit of it. – Basile Starynkevitch Dec 01 '13 at 11:19