简体   繁体   English

如何在makefile中为目标编写特定规则?

[英]How to write specific rule for a target in makefile?

I know the title is quite ambiguous but I just don't know how to describe my problem concisely. 我知道标题很含糊,但我只是不知道如何简单地描述我的问题。 Please edit that if you want. 如果需要,请进行编辑。

Currently my makefile is like the following: 目前,我的makefile如下所示:

CC = g++
CFLAGS = -Wall -g

TARGET = foobar
SRC_FILES = foo.cpp bar.cpp main.cpp
OBJ_FILES := $(SRC_FILES:.cpp=.o)

$(TARGET): $(OBJ_FILES)
    $(CC) $(CFLAGS) $^ -o $@

%.o: %.cpp %.h
    $(CC) $(CFLAGS) -c $<

clean:
    rm -rf *.o $(TARGET)

The problem is that this structure requires main.cpp to have a main.h header file, which I don't really have. 问题在于此结构要求main.cpp具有main.h头文件,而我实际上没有。 How can I handle this nicely? 我该如何处理好呢?

GCC (and probably Clang) can build a list of dependencies for you; GCC(也许还有Clang)可以为您建立一个依赖列表。 This way, you can simply make your object files from their source (cpp) file: 这样,您可以简单地从源文件(cpp)中创建目标文件:

depend: .depend

.depend: $(SRC_FILES)
        rm -f ./.depend
        $(CC) $(CFLAGS) -MM $^ -MF  ./.depend;

include .depend

%.o: %.cpp
    $(CC) $(CFLAGS) -c $<

You might also find interest in the makedepend tool. 您可能还会对makedepend工具感兴趣。

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

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