在makefile中规避重复库头和typedef的方法

Way of evading repetitive library headers and typedef in makefile

背景

假设我有这样的文件结构:

|Makefile
|build
|source
|-FunctionLinker.h
|-main.cpp
|-A.cpp
|-B.cpp
|-C.cpp

我想使用 Makefile 编译并将生成的 objective 文件保存在 build 文件夹中。这些文件的内容如下:

生成文件

CXX = g++ -std=c++11
CXXFLAGS = -c -Wall

OBJS = build/main.o build/A.o build/B.o build/C.o
all: Project
Project: $(OBJS)
    $(CXX) -o $@ $(OBJS)

build/%.o: source/%.cpp
    $(CXX) -o $@ $(CXXFLAGS) $<

main.cpp

#include <iostream>
#include <vector>
#include "FunctionLinker.h"

int main(){
    Vector ExampleVector = {1,2};
    Matrix ExampleMatrix = {{1,2},{3,4}};

    A(ExampleVector, ExampleMatrix); // which is void
    B(ExampleVector, ExampleMatrix); // which is also void
    VectorMatrix Res = C(ExampleVector, ExampleMatrix); // which returns struct

    for (int i=0; i<2; i++){
        std::cout << Res.Vector[i] << '\t'
    }
}

A.cppB.cpp差不多)

#include <iostream>
#include <vector>

typedef std::vector<double> Vector;
typedef std::vector<Vector> Matrix;

void A(Matrix& A, Vector& b){
    Some calculations...
}

C.cpp

#include <iostream>
#include <vector>

typedef std::vector<double> Vector;
typedef std::vector<Vector> Matrix;

VectorMatrix C(Matrix& A, Vector& b){
    Some calculations...
}

FunctionLinker.h

#ifndef FUNCTIONLINKER.H
#define FUNCTIONLINKER.H

#include <iostream>
#include <vector>

typedef std::vector<double> Vector;
typedef std::vector<Vector> Matrix;

struct VectorMatrix{ 
    Vector Vector;
    Matrix Matrix;
}; // I defined a struct here to allow a function to return multiple types

void A(Matrix A, Vector b);
void B(Matrix A, Vector b);
VectorMatrix C(Matrix A, Vector b);

#endif

问题

所以 Makefile 非常有效,但我怀疑这是否是最有效的做法。因为下面的代码

#include <iostream>
#include <vector>

typedef std::vector<double> Vector;
typedef std::vector<Vector> Matrix;

相当多余,所以我想找一个更"succinct"的方法来练习。任何帮助将不胜感激。

头文件的意义在于,您可以 include 在每个需要一些重复代码行的源文件中使用它们。因此,如果您在所有源文件中添加 #include "FunctionLinker.h",则可以删除多余的代码行。

请注意,这与生成文件无关。问题和解决方案在您的 C++ 代码中。