简体   繁体   English

如果更改,GNU make不能正确构建头文件

[英]GNU make does not build headers correctly if changed

I have this makefile: 我有这个makefile:

CC=g++

CFLAGS=-c -Wall

all: hello

hello: main.o client.o
        $(CC) main.o client.o -o hello

client.o: client.cpp client.h
        $(CC) $(CFLAGS) client.cpp -o client.o

main.o: main.cpp
        $(CC) $(CFLAGS) main.cpp -o main.o

clean:
        rm -rf *o hello

Whenever I make changes in hello.h, client.o is rebuilt when I execute make. 每当我在hello.h中进行更改时,执行make时都会重新构建client.o。 But when I try the resulting executable ./hello the change does not seem to happen. 但是,当我尝试生成的可执行文件./hello时,似乎没有发生更改。

The change is only reflected on ./hello if I add client.h to the main.o: rule like that 仅当我将client.h添加到main.o:规则时,更改才会反映在./hello上

main.o: main.cpp client.h
        $(CC) $(CFLAGS) main.cpp -o main.o

This will make things very difficult to maintain my code, any idea how to solve this problem? 这将使维护我的代码变得非常困难,有什么想法如何解决这个问题?

Edit: tried this change: 编辑:尝试此更改:

main.o: main.cpp
        $(CC) $(CFLAGS) -MD main.cpp -o main.o

but did not help. 但没有帮助。

UPDATE (final version): 更新(最终版本):

TARGET = hello

CC = g++

CPPFLAGS = -Wall -MP -MD

LINKER = g++ -o
LFLAGS = -Wall

SRCDIR = src
OBJDIR = obj
BINDIR = bin

SOURCES := $(wildcard $(SRCDIR)/*.cpp)
INCLUDES := $(wildcard $(SRCDIR)/*.h)
OBJECTS  := $(SOURCES:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS := $(SOURCES:$(SRCDIR)/%.cpp=$(OBJDIR)/%.d)

RM = rm -rf

DIR_GUARD = mkdir -p $(@D)

$(BINDIR)/$(TARGET): $(OBJECTS)
        @$(DIR_GUARD)
        @$(LINKER) $@ $(LFLAGS) $(OBJECTS)
        @echo "Linking complete!"

$(OBJECTS): $(OBJDIR)/%.o: $(SRCDIR)/%.cpp
        @$(DIR_GUARD)
        @$(CC) $(CPPFLAGS) -c $< -o $@
        @echo "Compiled "$<" successfully!"

-include $(DEPS)

.PHONEY: clean
clean:
        @$(RM) $(OBJDIR)/* $(BINDIR)/*
        @echo "Cleanup complete!"

Thanks guys for all the help, you are truly amazing. 谢谢大家的帮助,您真是太了不起了。

The problem is that the dependency of main.o on client.h is not specified in your Makefile . 问题是在您的Makefile未指定main.oclient.h的依赖关系。 Use: 采用:

main.o: main.cpp client.h
        $(CC) $(CFLAGS) main.cpp -o main.o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM