Reputation: 332
Say I have this structure of files:
|Makefile
|build
|source
|-FunctionLinker.h
|-main.cpp
|-A.cpp
|-B.cpp
|-C.cpp
where I would like to compile using Makefile
and save the resulting objective files in build
folder. The contents of these files are as follows:
Makefile
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.cpp (B.cpp is almost similar)
#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
So Makefile
perfectly works, but I doubt if it is the most effective practice. Because the following codes
#include <iostream>
#include <vector>
and
typedef std::vector<double> Vector;
typedef std::vector<Vector> Matrix;
are quite redundant, so I would like to find a more "succinct" way to do the practice. Any help will be appreciated.
Upvotes: 1
Views: 165
Reputation: 28251
The point of header files is that you can include
them in each source file which needs some repetitive lines of code. So if you add #include "FunctionLinker.h"
in all your source files, you can delete your redundant lines of code.
Please note that this has nothing to do with the makefile. The problem and solution are within your c++ code.
Upvotes: 3