c++ - 在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;
相当多余,所以我想找到一种更“简洁”的方法来进行练习。任何帮助将不胜感激。
解决方案
头文件的重点是您可以include
在每个需要一些重复代码行的源文件中使用它们。因此,如果您添加#include "FunctionLinker.h"
所有源文件,您可以删除多余的代码行。
请注意,这与 makefile 无关。问题和解决方案在您的 c++ 代码中。
推荐阅读
- tensorflow2.0 - 如何在 Colab 上使用 TPU 迁移 Learn
- html - 对齐css和html中的图标
- json - 在 SQL Server 中更新 JSON 列中的多个属性
- linux - 无法使用 ImageMagick 打开 .jpg、.png 或 .tif 文件,只能使用 .gif 文件
- python - `isinstance` 与 `collecitons.abc.Collection` 和 `collections.abc.Mapping` 的不同结果
- vb.net - VB.NET 在拖放时检查 keydown
- java - 通过 Maven / Eclipse 导入 Spotify API 客户端库
- python - 带有 configparser 的打开函数的 TypeError
- azure - 在 terraform 中,如何为 azure 中的应用服务设置新的路径映射?
- android - 浏览器的 ADB 查询