r/commandline • • 6h ago

Help Why does this Makefile always run ld?

If I run make after a clean, it compiles and links. Then if I immediately run make a second time, it links again. Shouldn't nothing happen the second time?

Commands:

$ make clean
rm -f rocco obj/rocco.o

$ make
/home/linuxbrew/.linuxbrew/bin/nasm -f elf32 -o obj/rocco.o src/rocco.asm
ld -m elf_i386 -o rocco obj/rocco.o

$ make
ld -m elf_i386 -o rocco obj/rocco.o

Makefile:

EXE=rocco
LD=ld
LDFLAGS=-m elf_i386 -o
NASM=/home/linuxbrew/.linuxbrew/bin/nasm
NASMFLAGS=-f elf32 -o
OBJ=rocco.o
OBJDIR=obj
SRC=rocco.asm
SRCDIR=src
        
all: src/rocco

$(OBJDIR)/$(OBJ): $(SRCDIR)/$(SRC)
        $(NASM) $(NASMFLAGS) $(OBJDIR)/$(OBJ) $(SRCDIR)/$(SRC)

$(SRCDIR)/$(EXE): $(OBJDIR)/$(OBJ)
        $(LD) $(LDFLAGS) $(EXE) $(OBJDIR)/$(OBJ)

clean:
        rm -vf $(EXE) $(OBJDIR)/$(OBJ)
4 Upvotes

3 comments sorted by

6

u/vivekkhera 6h ago

Your dependency is looking to build src/rocco but builds ./rocco so it is never satisfied.

3

u/t1nkl 5h ago

the target is src/rocco but ld writes ./rocco (the -o $(EXE) part). make checks whether src/rocco exists and is newer than the .o, it never exists, so it relinks every time. name the target after the file the recipe actually creates:

all: $(EXE)

$(EXE): $(OBJDIR)/$(OBJ)

$(LD) $(LDFLAGS) $@ $<

$@ is the target and $< the first prerequisite, so the name can't drift again. also add .PHONY: all clean, so a file called clean or all can't break those targets.

1

u/AutoModerator 6h ago

Every new subreddit post is automatically copied into a comment for preservation.

User: I0I0I0I, Flair: Help, Title: Why does this Makefile always run ld?

If I run make after a clean, it compiles and links. Then if I immediately run make a second time, it links again. Shouldn't nothing happen the second time?

Commands:

$ make clean
rm -f rocco obj/rocco.o

$ make
/home/linuxbrew/.linuxbrew/bin/nasm -f elf32 -o obj/rocco.o src/rocco.asm
ld -m elf_i386 -o rocco obj/rocco.o

$ make
ld -m elf_i386 -o rocco obj/rocco.o

Makefile:

NASM=/home/linuxbrew/.linuxbrew/bin/nasm
NASMFLAGS=-f elf32 -o
LD=ld
LDFLAGS=-m elf_i386 -o
EXE=rocco
OBJ=rocco.o
SRC=rocco.asm
SRCDIR=src
OBJDIR=obj

all: src/rocco

$(OBJDIR)/$(OBJ): $(SRCDIR)/$(SRC)
        $(NASM) $(NASMFLAGS) $(OBJDIR)/$(OBJ) $(SRCDIR)/$(SRC)

$(SRCDIR)/$(EXE): $(OBJDIR)/$(OBJ)
        $(LD) $(LDFLAGS) $(EXE) $(OBJDIR)/$(OBJ)

clean:
        rm -vf $(EXE) $(OBJDIR)/$(OBJ)

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.