简体   繁体   English

GNU Makefile规则和依赖项

[英]GNU makefile rules and dependencies

I've been doing a lot of reading on how to write makefiles to build an application on Linux but I'm massively confused about the many different ways to apparently achieve the same goal. 我一直在阅读有关如何编写makefile来在Linux上构建应用程序的大量书籍,但是我对显然可以实现同一目标的许多不同方法感到困惑。

This is what I have come up with so far to build an archive. 到目前为止,这是我提出的用于建立存档的内容。

SHELL = /bin/sh

CXX = g++
DEBUG = -g
CXXFLAGS = -std=c++11 -Wall -pedantic #-Wextra
CPPFLAGS =  -I. \
            -I./include

SOURCES =   foo1.cpp \
            foo2.cpp \
            foo3.cpp

OBJECTS = $(SOURCES:.cpp=.o)

The following rule successfully compiles each source file into an object file and then creates an archive: 以下规则将每个源文件成功编译为目标文件,然后创建一个归档文件:

libfoo.a: $(OBJECTS)
    ar rvcs $@ $(OBJECTS)

%.o: src/%.cpp ./include/%.h
    $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) -o $@ $< 

This also does the same thing: 这也做同样的事情:

libfoo.a: $(OBJECTS)
    ar rvcs $@ $(OBJECTS)

$(OBJECTS) : %.o:src/%.cpp
    $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) -o $@ $< 

However, this fails with an error that there is no rule to make target 'foo1.o:%.h 但是,此操作失败,并显示一个错误,即没有规则可以使目标'foo1.o:%。h

libfoo.a: $(OBJECTS)
    ar rvcs $@ $(OBJECTS)

$(OBJECTS) : %.o:src/%.cpp %.o:%.h
    $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) -o $@ $< 

Can someone please explain why it doesn't work and which approach is best? 有人可以解释为什么它不起作用,哪种方法最好吗?

The first option lists the header files as dependencies but the second option doesn't. 第一个选项将头文件列出为依赖项,而第二个选项则没有。 That is my motivation for the third option. 这是我选择第三个选项的动机。

How do I list the headers as dependencies using options 2 or 3? 如何使用选项2或3将标头列出为依赖项?

TIA TIA

The feature you're using in try #2 and try #3 is static pattern rules and the syntax looks like this: 在尝试#2和尝试#3中使用的功能是静态模式规则 ,其语法如下所示:

<targets...> : <target-pattern> : <prerequisites...>

There can only be two colons, not three. 只能有两个冒号,不能三个。 You should write your try #3 above as: 您应该将上面的尝试3写为:

$(OBJECTS) : %.o : src/%.cpp %.h
        $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) -o $@ $< 

Note one critical thing: this rule will FAIL if you ever create any .cpp file which does not have an associated .h file. 注意一件重要的事情:如果您创建任何没有关联的.h文件的.cpp文件,此规则将失败。 Just sayin'. 只是在说'。

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

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