首页 > 解决方案 > 在makefile中规避重复库头和typedef的方法

问题描述

背景

假设我有这种文件结构:

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

我想在哪里编译使用Makefile并将生成的目标文件保存在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) $<

主文件

#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.cpp ( B.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...
}

函数链接器.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;

相当多余,所以我想找到一种更“简洁”的方法来进行练习。任何帮助将不胜感激。

标签: c++include

解决方案


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

请注意,这与 makefile 无关。问题和解决方案在您的 c++ 代码中。


推荐阅读