单个make文件用于多个main.cpp文件

时间:2015-12-01 15:38:53

标签: c++ makefile

我有一个项目需要计算多个情况,所有情况都使用相同的标头和依赖项。目录层次结构就是这样。

/src/Chapter_4/Exercise_4.7.cpp
/src/Chapter_4/Exercise_4.9.cpp
/src/Chapter_4/Exercise_4.12.cpp (etc...)
/src/Chapter_4/Makefile

/src/header1.h
/src/header2.h (etc...)

我想让单个Makefile让我运行命令“make Exercise_4。(what)”并编译该特定的Exercise文件。每次我想编译不同的练习时,我真的不想编辑Makefile。

请记住,我使用make文件非常非常新。

2 个答案:

答案 0 :(得分:0)

我认为这样的事情会起作用

%: %.cpp
    g++ $< -I../ -o $@

规则名称与cpp文件相同。因此,如果您想编译Excercise_4.cpp,只需使用make Excercise_4$<引用您的输入参数,$@到目标名称。

答案 1 :(得分:0)

根据您的依赖关系(或缺少依赖关系),您根本不需要编写Makefile。只需做:

private class createNewStudentListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        try
        {
            Student s = new Student(enterFirstName.getText(), enterLastName.getText());
            File newStudent;
            newStudent = new File("Students.bin");
            FileOutputStream outStream = new FileOutputStream("Students.bin", newStudent.exists());
            ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream);
            objectOutputFile.writeObject(s);
            JOptionPane.showMessageDialog(null, "The new student was added successfully");
            String id = Integer.toString(s.getID());
            IDNUM.setText(id);
            s = null;
            objectOutputFile.close();
        }
        catch (emptyString a)
        {
            JOptionPane.showMessageDialog(null, a.getMessage());
        } catch (Exception a) {
            JOptionPane.showMessageDialog(null, a.getMessage());
        }
    }
}

...与$ cd /src/Chapter_4 $ make Exercice_4.x 匹配您要编译的文件之一就足够了,因为Make有很多内置的隐式规则,并且它有一个从源文件编译可执行文件同名。

你可以这样做:

x

...输出是:

$ make -p | grep -C2 "%.cpp"

使用类似的命令,我们看到%: %.cpp # recipe to execute (built-in): $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@ 扩展为$(LINK.cpp),扩展为$(LINK.cc)

因此,当您致电$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)时,它会执行以下内容:

make Exercice_4.19

如果您愿意,可以说,添加警告标志或使用某个标准版本,您可以直接添加标记:

g++     Exercice_4.19.cpp   -o Exercice_4.19

或者将它写在你的Makefile中:

$ make Exercice_4.19 CXXFLAGS="-std=c++11 -Wall"
g++ -std=c++11 -Wall    Exercice_4.19.cpp   -o Exercice_4.19

然后像以前一样打电话:

CXXFLAGS := -std=c++11 -Wall

对于这么简单的任务,你根本不需要为编写规则而烦恼。

相关问题