简体   繁体   中英

How to reuse target in Makefile?

Basically, I want to make this code in file Makefile executable:

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 . 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. 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. 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.

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 .

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 .

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 $@

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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