简体   繁体   English

如何使这个Makefile更通用?

[英]How can I make this Makefile more generic?

I'm brushing up on C++ by completing many small programs, each contained in a single cpp file. 我正在通过完成许多小程序来刷新C ++,每个程序都包含在一个cpp文件中。 I also want to learn a little bit more about Makefiles, and decided to write a Makefile that will compile all of my little programs and produce an executable per program. 我还想学习更多关于Makefiles的内容,并决定编写一个Makefile来编译我的所有小程序并为每个程序生成一个可执行文件。 With my current Makefile, I have to: 使用我当前的Makefile,我必须:

  1. Append the name to the end of "BINARIES" 将名称附加到“BINARIES”的末尾

  2. Copy the repeated target and replace the target name with the binary name 复制重复的目标并使用二进制名称替换目标名称

How can I edit this Makefile to be even more generic, so that I can simply append the name of my new program to the end of "BINARIES" and not have to continue to copy and paste the repeated targets? 如何编辑这个Makefile更加通用,这样我就可以简单地将我的新程序的名称附加到“BINARIES”的末尾,而不必继续复制和粘贴重复的目标?

    BIN=./bin/
    SOURCE=./src/
    CXX=g++
    CXXFLAGS=-g -c -Wall
    BINARIES=sums-in-loop sum-in-loop sum-of-two
    RM=rm -f

    all: sums-in-loop sum-in-loop sum-of-two

    sums-in-loop:
        $(CXX) $(CXXFLAGS) $(SOURCE)$@.cpp -o $(BIN)$@ 

    sum-in-loop:
        $(CXX) $(CXXFLAGS) $(SOURCE)$@.cpp -o $(BIN)$@ 

    sum-of-two:
        $(CXX) $(CXXFLAGS) $(SOURCE)$@.cpp -o $(BIN)$@ 

    clean:
        $(RM) $(BIN)*

The usual way is to use pattern rules: 通常的方法是使用模式规则:

BIN=bin
SOURCE=src
CXX=g++
CXXFLAGS=-g -Wall
BINARIES=sums-in-loop sum-in-loop sum-of-two
RM=rm -f

all: $(addprefix $(BIN)/,$(BINARIES))

$(BIN)/%: $(SOURCE)/%.cpp
    $(CXX) $(CXXFLAGS) $< -o $@ 

clean:
    $(RM) $(BIN)/*

With loops in Makefile, you can do something like : 使用Makefile中的循环,您可以执行以下操作:

$(foreach bin,$(BINARIES),$(CXX) $(CXXFLAGS) $(SOURCE)$(dir).cpp -o $(BIN)$dir;)

You can find some info --> http://www.gnu.org/software/make/manual/make.html#Foreach-Function 你可以找到一些信息 - > http://www.gnu.org/software/make/manual/make.html#Foreach-Function

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

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