3

I have makefile where I have noticed somethign peculiar.

On the line marked with <------, if I put $(OBJECTS) instead of String.o the compilation fails. But I defined OBJECTS=$(String.o), why does that work this way?

LIBS=-ldl $(OPTLIBS)
PREFIX?=string-automaton/
DESTDIR=/home/jenia/learn-c-the-hard-way/lib2/
CFLAGS=-g -O2 -Wall -Wextra -rdynamic -DNDEBUG -Llibstrl


OBJECTS=$(String.o)

TARGET=build/lib_String.a
SO_TARGET=$(patsubst %.a,%.so,$(TARGET))

# The Target Build
all: build $(TARGET) $(SO_TARGET) 

$(TARGET): CFLAGS += -fPIC
$(TARGET): $(OBJECTS) 
    ar rcs $@ $(OBJECTS)   
    ranlib $@

$(SO_TARGET): $(TARGET) $(OBJECTS)   
    $(CC) -shared -o $@  String.o     # <----------- $(OBJECTS) woud fail

build:
    @mkdir -p build
    @mkdir -p bin

clean:
    rm -rf build $(OBJECTS) $(TESTS)
    rm -f tests/tests.log
    find . -name "*.gc*" -exec rm {} \;
    rm -rf `find . -name "*.dSYM" -print`

# The Install
install: all
    install -d $(DESTDIR)/$(PREFIX)/lib/
    install $(TARGET) $(DESTDIR)/$(PREFIX)/lib/

Also, as a follow up question, if I add $(OBJECTS) to the line <----- and remove $(OBJECTS) from the line before it then it compiles. Like this:

$(SO_TARGET): $(TARGET) 
$(CC) -shared -o $@ $(OBJECTS)    

So can someone please answer me why $(OBJECTS) doesn't resolve to String.o on line <-----?

Thanks

Jenia Ivanov
  • 2,485
  • 3
  • 41
  • 69
  • 1
    `$(...)` is variable expansion in a makefile. So `$(String.o)` tells make to expand the variable with the name `String.o` and use its value. As you likely don't have any such variable you get an empty value in `OBJECTS`. – Etan Reisner Mar 11 '16 at 03:57

1 Answers1

6

It is because $(String.o) will resolve to another string -- probably an empty string if String.o is not defined.

I guess you should replace

OBJECTS=$(String.o)

with

OBJECTS=String.o
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • sorry, I changed the very last phrase right after you answered. Just to make sure, does you answer still hold after the change? before you answered the last line was: So can someone please answer me why `$(OBJECTS)` doesn't resolve to `$(String.o)` on line `<-----`? – Jenia Ivanov Mar 11 '16 at 03:05
  • Yes, it wll be the same answer. – MikeCAT Mar 11 '16 at 03:06
  • thanks very much. It compiles perfectly now. I need to wait 4 more minutes to accept it. Again, thanks kindly – Jenia Ivanov Mar 11 '16 at 03:09