简体   繁体   English

Makefile中的target如何复用?

[英]How to reuse target in Makefile?

Basically, I want to make this code in file Makefile executable:基本上,我想让文件Makefile中的代码可执行:

targ: file1.cpp
    g++ file1.cpp -o file1

targ: file2.cpp
    g++ file2.cpp -o file2

targ: file3.cpp
    g++ file3.cpp -o file3

I know that I could combine it into something like this:我知道我可以把它组合成这样的东西:

targ: file1.cpp file2.cpp file3.cpp
    g++ file1.cpp -o file1
    g++ file2.cpp -o file2
    g++ file3.cpp -o file3

But I want it to only run the corresponding line when the corresponding file is updated.但我希望它只在更新相应文件时运行相应的行。 How do I do so?我该怎么做? Thanks in advance.提前致谢。

You have to set up the relations right.您必须正确设置关系。

Example:例子:

targ: file1 file2 file3

file1: file1.cpp
    g++ file1.cpp -o file1

file2: file2.cpp
    g++ file2.cpp -o file2

file3: file3.cpp
    g++ file3.cpp -o file3

That says:说的是:

if you want to build targ ( you should also make it PHONY ), make sees that you will build file1 file2 and file3 .如果您想构建targ (您也应该将其设为 PHONY ),make 会看到您将构建file1 file2file3 And for this, you have the explicit rules.为此,您有明确的规则。 Thats it!而已!

In a makefile rule, whatever you put in the left hand side of : is the product/result of running the commands below.在 makefile 规则中,无论您在:左侧放置什么,都是运行以下命令的产品/结果。 In your example, you are saying that targ product is made in three different ways, which is confusing because the way of creating targ is ambiguous.在您的示例中,您说targ产品以三种不同的方式制造,这令人困惑,因为创建targ的方式不明确。 What you probably wanted to say is that in order to succesfully build targ , you need to create three executables file1 file2 and file3 , each built using their corresponding .cpp files.您可能想说的是,为了成功构建targ ,您需要创建三个可执行文件file1 file2file3 ,每个都使用相应的.cpp文件构建。

For that purpose you can rely on the implicit rules .为此,您可以依赖隐式规则 For a C++ executable, the implicit recipe is going to look for a .o file with the same name, and for that .o file it is going to look for several file name alternatives including .cpp .对于 C++ 可执行文件,隐式配方将查找具有相同名称的.o文件,对于该.o文件,它将查找包括.cpp在内的多个文件名替代项。

So basically something like this should be enough:所以基本上这样的事情就足够了:

CXX=g++
targ: file1 file2 file3

The implicit recipe uses variables such as CXX to define the C++ compiler, CPPFLAGS to define the preprocessor flags ( -I , -D , etc.) the compiler and linker flags CXXFLAGS LDFLAGS and what libraries you are going to link against LDLIBS .隐式配方使用CXX变量定义 C++ 编译器, CPPFLAGS定义预处理器标志( -I-D等)编译器和 linker 标志CXXFLAGS LDFLAGS以及您要链接的LDLIBS

If you do not want to rely on implicit rules, you can create a pattern recipe and use automatic variables :如果您不想依赖隐式规则,则可以创建模式配方并使用自动变量

target: file1 file2 file3

%: %.cpp
  g++ $^ -o $@

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

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