Module 10: Building a CFD Solver from Scratch
Connect governing equations, finite-volume discretization, algebraic solvers, boundary conditions, and verification into a complete computational fluid dynamics solver using a structured C++ workflow.
1. Introduction: From Numerical Methods to a Working Solver
In the previous nine modules, we developed the mathematical and numerical foundations of computational fluid dynamics.
We studied how physical laws produce governing equations, how those equations are discretized, how algebraic systems are solved, and how numerical predictions are verified and validated.
The next step is to connect these ideas into a working computational program.
A CFD solver is not simply a collection of equations. It is a coordinated system of data structures, numerical algorithms, boundary conditions, linear solvers, convergence checks, and post-processing procedures.
A typical CFD calculation follows this sequence:
- Define the physical problem.
- Create the computational mesh.
- Initialize the solution fields.
- Specify physical properties and boundary conditions.
- Assemble the discrete equations.
- Solve the algebraic systems.
- Update the solution fields.
- Check convergence and conservation.
- Write results for visualization and analysis.
- Verify the result against a known reference.
In this module, we will design a small solver architecture and use a one-dimensional steady diffusion problem as the first complete implementation.
This is a deliberately simple starting point. The objective is to understand the structure of a numerical solver before adding the coupled equations and complexity of full fluid flow.
2. Learning Objectives
By the end of this module, you should be able to:
- Explain the main components of a CFD solver.
- Separate physical models from numerical methods and software infrastructure.
- Design basic mesh, field, boundary-condition, and solver classes in C++.
- Implement a finite-volume discretization for a diffusion problem.
- Assemble and solve a tridiagonal algebraic system.
- Check residuals and compare numerical results with an analytical solution.
- Organize a numerical project for testing, debugging, and extension.
- Understand how a simple scalar solver can evolve toward an incompressible Navier–Stokes solver.
3. What Is a CFD Solver?
A CFD solver is software that approximates the solution of mathematical equations describing fluid motion and associated transport processes.
The complete process can be represented as
Each stage has a distinct responsibility.
3.1 Physical model
The physical model defines the equations and assumptions used to describe the system.
Examples include:
- Incompressible Navier–Stokes equations.
- Compressible flow equations.
- Heat-transfer equations.
- Multiphase-flow models.
- Turbulence models.
- Particle-fluid interaction models.
The physical model determines which quantities must be calculated and how they interact.
3.2 Numerical method
The numerical method converts the governing equations into a finite set of algebraic equations.
Typical components include:
- Spatial discretization.
- Time integration.
- Convective flux approximation.
- Diffusive flux approximation.
- Source-term treatment.
- Boundary-condition discretization.
For example, a finite-volume method converts a conservation law into a balance of fluxes across the faces of each cell.
3.3 Algebraic solver
After discretization, the numerical problem often takes the form
where:
- is the coefficient matrix.
- contains the unknown discrete values.
- contains known contributions from sources and boundary conditions.
A linear solver computes an approximation to .
Depending on the problem, the matrix may be tridiagonal, sparse, symmetric, nonsymmetric, or part of a larger coupled system.
3.4 Solver infrastructure
The infrastructure manages the computational work surrounding the numerical method.
It includes:
- Mesh storage.
- Field storage.
- Boundary conditions.
- Physical properties.
- Linear-system assembly.
- Convergence monitoring.
- File input and output.
- Logging and diagnostics.
Separating these responsibilities makes a solver easier to test and extend.
4. Begin with a Simple Physical Problem
Before implementing a complete fluid-flow solver, consider steady one-dimensional heat conduction through a slab.
Although heat conduction is not itself a fluid-flow problem, it is an excellent first test of the infrastructure used in many CFD solvers.
The same basic concepts—control volumes, fluxes, boundary conditions, matrix assembly, and iterative or direct solution—also appear in fluid-flow calculations.
4.1 Governing equation
Consider a slab of length with constant thermal conductivity and no internal heat generation.
The governing equation is
For constant conductivity,
The boundary conditions are
The analytical solution is
The solution is linear because the temperature gradient is constant throughout the slab.
4.2 Why this is a useful first solver
This problem allows us to test several important numerical components independently:
- Cell-centred field storage.
- Finite-volume diffusion coefficients.
- Boundary-condition treatment.
- Matrix assembly.
- Linear-system solution.
- Numerical error calculation.
- Heat-flux conservation.
If the program cannot reproduce this simple problem, adding fluid-flow equations will make debugging more difficult rather than easier.
5. Design the Solver Architecture
A useful design separates the solver into small components with clear responsibilities.
A conceptual architecture is
CFD Solver
├── Mesh
│ ├── Cell centres
│ ├── Cell volumes
│ └── Face locations
├── Fields
│ ├── Temperature
│ ├── Velocity
│ └── Pressure
├── Physical Models
│ ├── Material properties
│ └── Governing equations
├── Discretization
│ ├── Diffusion
│ ├── Convection
│ └── Transient terms
├── Linear Algebra
│ ├── Matrix assembly
│ └── Linear solvers
├── Boundary Conditions
├── Convergence Monitoring
└── Results and Post-processing
This is a conceptual structure, not a requirement to create every component immediately.
For the first implementation, we only need a one-dimensional mesh, a temperature field, a diffusion discretization, a tridiagonal solver, and basic verification.
5.1 Mesh
The mesh defines where the unknowns are stored and how the computational domain is divided.
For a uniform one-dimensional mesh,
where is the number of cells.
The centre of cell , using zero-based indexing, is
The first and last cell centres are therefore half a cell away from the domain boundaries.
This distinction matters when applying boundary conditions.
5.2 Field
A field stores a physical quantity at the mesh locations.
For a cell-centred scalar field, we can write
In C++, a simple representation is a std::vector<double>.
5.3 Physical properties
The conductivity is constant in this example.
In a more general solver, physical properties may vary spatially or depend on the solution.
For example,
would introduce a temperature-dependent conductivity and potentially require nonlinear solution procedures.
Keep the first implementation simple and introduce complexity only when the existing method is understood and verified.
6. Derive the Finite-Volume Equation
Before writing code, derive the discrete equations.
This is an essential practice: the implementation should follow a documented mathematical formulation rather than relying on trial-and-error changes to coefficients.
6.1 Integrate over a control volume
For a cell-centred finite-volume method, integrate the governing equation over a cell.
In one dimension, this gives
Multiplying by the appropriate cross-sectional area gives the corresponding heat-flow balance.
For a constant cross-sectional area, that area cancels from the final temperature equation.
6.2 Approximate the face gradients
For an interior face between adjacent cell centres,
Similarly, at the west face,
Substituting these approximations into the integrated equation gives
Rearranging,
This is the standard interior finite-volume equation for constant-property one-dimensional diffusion on a uniform mesh.
6.3 Apply the boundary conditions
The boundary temperatures are prescribed at the physical boundaries, not at the first and last cell centres.
The distance from the first cell centre to the left boundary is .
The west-face diffusive contribution is therefore proportional to
The corresponding east-boundary expression uses the distance between the last cell centre and the right boundary.
After dividing by the common factor , the first-cell equation becomes
The last-cell equation becomes
These boundary equations are consistent with a cell-centred mesh and the half-cell distances to the prescribed boundary temperatures.
6.4 Assemble the complete system
For cells, the system is
For example, with four cells,
The matrix is tridiagonal, so storing every entry of a dense matrix is unnecessary.
A tridiagonal representation stores only three diagonals:
- Lower diagonal.
- Main diagonal.
- Upper diagonal.
This reduces memory use and allows an efficient direct solution.
7. Implement the Tridiagonal Solver
The Thomas algorithm solves a tridiagonal system using forward elimination followed by back substitution.
Consider
where , , and represent the lower, main, and upper diagonal coefficients.
7.1 Forward elimination
The first row is normalized:
For subsequent rows,
The final upper-diagonal coefficient can be treated as zero because no unknown exists beyond the last row.
The implementation must check that the denominators are nonzero and numerically safe.
7.2 Back substitution
The last unknown is
The remaining unknowns are computed in reverse order:
The Thomas algorithm requires work proportional to the number of unknowns, making it efficient for one-dimensional diffusion problems.
However, it is not a general-purpose solver for arbitrary sparse matrices. More complex CFD systems require other linear solvers.
8. Complete C++ Implementation
The following program solves the steady heat-conduction problem using the finite-volume equations derived above.
It writes the numerical solution and analytical solution to a CSV file and reports the maximum absolute error.
Save the code as main.cpp.
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
struct Mesh1D {
double length;
int cells;
double dx;
Mesh1D(double length_, int cells_)
: length(length_),
cells(cells_),
dx(length_ / static_cast<double>(cells_)) {
if (length <= 0.0) {
throw std::invalid_argument(
"Domain length must be positive."
);
}
if (cells < 2) {
throw std::invalid_argument(
"At least two cells are required."
);
}
}
double centre(int i) const {
return (static_cast<double>(i) + 0.5) * dx;
}
};
struct TridiagonalSystem {
std::vector<double> lower;
std::vector<double> diagonal;
std::vector<double> upper;
std::vector<double> rhs;
explicit TridiagonalSystem(int n)
: lower(n, 0.0),
diagonal(n, 0.0),
upper(n, 0.0),
rhs(n, 0.0) {}
};
std::vector<double> solveThomas(
const TridiagonalSystem& system
) {
const int n =
static_cast<int>(system.diagonal.size());
if (n == 0 ||
system.lower.size() != system.diagonal.size() ||
system.upper.size() != system.diagonal.size() ||
system.rhs.size() != system.diagonal.size()) {
throw std::invalid_argument(
"Invalid tridiagonal system dimensions."
);
}
std::vector<double> cPrime(n, 0.0);
std::vector<double> dPrime(n, 0.0);
const double scale = std::max(
1.0,
*std::max_element(
system.diagonal.begin(),
system.diagonal.end(),
[](double a, double b) {
return std::abs(a) < std::abs(b);
}
)
);
const double tolerance =
100.0 * std::numeric_limits<double>::epsilon()
* std::abs(scale);
if (std::abs(system.diagonal[0]) <= tolerance) {
throw std::runtime_error(
"Unsafe pivot in Thomas algorithm."
);
}
cPrime[0] =
system.upper[0] / system.diagonal[0];
dPrime[0] =
system.rhs[0] / system.diagonal[0];
for (int i = 1; i < n; ++i) {
const double denominator =
system.diagonal[i]
- system.lower[i] * cPrime[i - 1];
if (std::abs(denominator) <= tolerance) {
throw std::runtime_error(
"Unsafe pivot in Thomas algorithm."
);
}
cPrime[i] =
(i == n - 1)
? 0.0
: system.upper[i] / denominator;
dPrime[i] =
(system.rhs[i]
- system.lower[i] * dPrime[i - 1])
/ denominator;
}
std::vector<double> solution(n, 0.0);
solution[n - 1] = dPrime[n - 1];
for (int i = n - 2; i >= 0; --i) {
solution[i] =
dPrime[i] - cPrime[i] * solution[i + 1];
}
return solution;
}
TridiagonalSystem assembleHeatEquation(
int cells,
double leftTemperature,
double rightTemperature
) {
TridiagonalSystem system(cells);
// Left boundary:
// 3*T[0] - T[1] = 2*T_left
system.diagonal[0] = 3.0;
system.upper[0] = -1.0;
system.rhs[0] = 2.0 * leftTemperature;
// Interior cells:
// -T[i-1] + 2*T[i] - T[i+1] = 0
for (int i = 1; i < cells - 1; ++i) {
system.lower[i] = -1.0;
system.diagonal[i] = 2.0;
system.upper[i] = -1.0;
system.rhs[i] = 0.0;
}
// Right boundary:
// -T[N-2] + 3*T[N-1] = 2*T_right
system.lower[cells - 1] = -1.0;
system.diagonal[cells - 1] = 3.0;
system.rhs[cells - 1] = 2.0 * rightTemperature;
return system;
}
double analyticalTemperature(
double x,
double length,
double leftTemperature,
double rightTemperature
) {
return leftTemperature
+ (rightTemperature - leftTemperature)
* x / length;
}
int main() {
const double length = 1.0;
const double conductivity = 10.0;
const double leftTemperature = 400.0;
const double rightTemperature = 300.0;
const int cells = 40;
if (conductivity <= 0.0) {
std::cerr
<< "Thermal conductivity must be positive.\n";
return 1;
}
try {
const Mesh1D mesh(length, cells);
const TridiagonalSystem system =
assembleHeatEquation(
cells,
leftTemperature,
rightTemperature
);
const std::vector<double> temperature =
solveThomas(system);
std::ofstream file("solution.csv");
if (!file) {
throw std::runtime_error(
"Could not open solution.csv."
);
}
file << "x,T_numerical,T_exact,absolute_error\n";
file << std::setprecision(12);
double maximumError = 0.0;
for (int i = 0; i < cells; ++i) {
const double x = mesh.centre(i);
const double exact =
analyticalTemperature(
x,
length,
leftTemperature,
rightTemperature
);
const double error =
std::abs(temperature[i] - exact);
maximumError =
std::max(maximumError, error);
file << x << ","
<< temperature[i] << ","
<< exact << ","
<< error << "\n";
}
const double heatFluxLeft =
-conductivity
* (temperature[0] - leftTemperature)
/ (mesh.dx / 2.0);
const double heatFluxRight =
-conductivity
* (rightTemperature
- temperature[cells - 1])
/ (mesh.dx / 2.0);
std::cout
<< "Steady 1D heat-conduction solver\n";
std::cout
<< "Number of cells: " << cells << "\n";
std::cout
<< "Maximum absolute error: "
<< maximumError << "\n";
std::cout
<< "Left boundary heat flux: "
<< heatFluxLeft << "\n";
std::cout
<< "Right boundary heat flux: "
<< heatFluxRight << "\n";
std::cout
<< "Results written to solution.csv\n";
}
catch (const std::exception& error) {
std::cerr << "Error: "
<< error.what() << "\n";
return 1;
}
return 0;
}
8.1 Important implementation note
The code uses std::numeric_limits, so add the following header to the includes:
#include <limits>
The pivot tolerance is a basic defensive check, not a complete assessment of matrix conditioning. For a production solver, numerical safeguards should be chosen according to the matrix scaling and solver requirements.
8.2 Compile and run
With a C++17-compatible compiler, run:
g++ -std=c++17 -O2 -Wall -Wextra -pedantic main.cpp -o heat_solver
Then execute:
./heat_solver
On Windows, the executable may be named heat_solver.exe.
The program should create solution.csv containing the cell-centre positions, numerical temperatures, analytical temperatures, and absolute errors.
8.3 What should you expect?
For the chosen boundary temperatures, the analytical solution is a straight line between 400 K and 300 K.
The numerical solution should reproduce that linear profile to floating-point precision for this particular constant-property problem and discretization, apart from small rounding effects.
The heat fluxes calculated from the first and last half-cell temperature differences should agree closely.
This is a useful verification result, but it does not demonstrate that the code can solve general convection, turbulent flow, or coupled heat transfer.
9. Improve the Code Structure
The initial program deliberately keeps the implementation compact. As the solver grows, separate its responsibilities.
One possible project structure is:
FirstPrinciplesCFD/
├── CMakeLists.txt
├── README.md
├── include/
│ ├── Mesh1D.hpp
│ ├── Field.hpp
│ ├── BoundaryConditions.hpp
│ ├── TridiagonalSystem.hpp
│ └── HeatConductionSolver.hpp
├── src/
│ ├── main.cpp
│ ├── TridiagonalSystem.cpp
│ └── HeatConductionSolver.cpp
├── tests/
│ ├── test_mesh.cpp
│ ├── test_linear_solver.cpp
│ └── test_heat_conduction.cpp
├── cases/
│ ├── baseline/
│ └── mesh_refinement/
├── scripts/
│ ├── run_study.py
│ └── plot_results.py
└── results/
The exact structure is not important by itself. What matters is that the code becomes easier to understand, test, and extend.
9.1 Keep physical equations separate from linear algebra
The heat-conduction solver should know how to construct the diffusion equations.
The tridiagonal solver should know how to solve a tridiagonal system.
The mesh should know the cell locations and spacing.
The output routine should write results.
This separation allows the same linear solver to be tested independently and potentially reused for other one-dimensional problems.
9.2 Use meaningful names
Prefer names such as:
thermalConductivitycellTemperatureleftBoundaryTemperaturemaximumAbsoluteError
over names that conceal physical meaning.
Readable code makes it easier to compare the implementation with the governing equations.
10. Add Automated Tests
A numerical solver should be tested at several levels.
10.1 Unit tests
Unit tests assess individual components.
Examples:
- Does the mesh calculate cell centres correctly?
- Does the tridiagonal solver solve a known system?
- Does the analytical temperature function return correct values?
- Does invalid mesh input produce a useful error?
10.2 Numerical verification tests
These compare the numerical solution against a known mathematical result.
For the heat-conduction problem, test:
at every cell centre.
Use a tolerance appropriate to the problem and arithmetic precision rather than requiring exact equality between floating-point numbers.
10.3 Conservation tests
Verify that the heat flux at the two boundaries agrees within a justified numerical tolerance.
For the steady source-free problem,
when both fluxes use the same positive coordinate direction.
Be careful with sign conventions: a heat flux expressed using outward normals at opposite boundaries will have opposite signs for the same through-flow of energy.
10.4 Regression tests
A regression test stores a trusted result for a fixed problem and checks that future changes do not cause an unexpected difference.
Regression tests should not replace analytical verification. They are most useful when combined with known physical or mathematical expectations.
11. Build a Mesh-Refinement Study
Once the baseline solver works, run the same physical problem on multiple meshes.
For example, choose
For each mesh, record:
- Cell count.
- Maximum absolute error.
- Root-mean-square error.
- Boundary heat-flux imbalance.
- Runtime.
A table might look like this:
| Cells | Maximum error | Heat-flux imbalance | Runtime |
|---|---|---|---|
| 10 | To be measured | To be measured | To be measured |
| 20 | To be measured | To be measured | To be measured |
| 40 | To be measured | To be measured | To be measured |
| 80 | To be measured | To be measured | To be measured |
Do not fill this table with assumed values. Generate the results from the program.
For this particular linear temperature problem, the standard discretization can reproduce the analytical cell-centre values to floating-point precision even on a coarse mesh. Consequently, it is not a strong test for observing second-order convergence.
To study the convergence order meaningfully, use a smooth nonlinear manufactured solution, such as the diffusion problem from Module 9, with the corresponding source term.
This illustrates an important verification principle: a test can confirm a useful property of a method without exercising every aspect of its accuracy.
12. From a Scalar Solver to a Fluid-Flow Solver
The heat-conduction solver provides a starting architecture, but incompressible fluid flow requires additional mathematical structure.
The governing equations are the continuity equation and momentum equations.
12.1 Continuity
For incompressible flow,
This states that the velocity field must be divergence-free.
12.2 Momentum
For a Newtonian fluid with constant properties and no additional body-force terms written explicitly, the momentum equation can be expressed as
where:
- is velocity.
- is pressure.
- is density.
- is kinematic viscosity.
This form assumes constant density and viscosity and uses a conservative convective representation consistent with incompressible flow.
A practical solver must also represent boundary conditions, body forces when relevant, and any additional physical models.
12.3 Why pressure–velocity coupling is needed
The momentum equation contains pressure, but pressure is not governed by an independent thermodynamic equation in the standard incompressible formulation.
Instead, pressure helps enforce the continuity constraint.
A pressure–velocity coupling method constructs a provisional velocity, solves a pressure-related correction equation, and updates the velocity and face fluxes to reduce the continuity error.
Methods include SIMPLE, PISO, and PIMPLE, which were introduced in Module 8.
The exact procedure depends on the solver formulation and discretization.
12.4 Additional components required
A more complete incompressible solver will need:
- Vector velocity fields.
- Pressure fields.
- Face fluxes.
- Momentum-equation assembly.
- Pressure-correction or pressure-equation assembly.
- Gradient and divergence operators.
- Boundary-condition handling.
- Pressure reference treatment.
- Iterative coupling.
- Continuity and momentum diagnostics.
The architecture should grow to support these requirements without embedding all numerical operations in one large function.
13. Suggested Development Roadmap
A sensible progression is to add one capability at a time.
Stage 1: Scalar diffusion
Implement the one-dimensional steady heat-conduction problem.
Verify it against an analytical solution and check boundary heat fluxes.
Stage 2: General source terms
Extend the scalar equation to include a source term.
Test the implementation using a manufactured solution.
Stage 3: Transient diffusion
Add a time derivative and implement explicit or implicit time integration.
Verify temporal accuracy and stability against an analytical transient solution.
Stage 4: Convection–diffusion
Add convective fluxes and compare central differencing with upwind discretization.
Study boundedness, numerical diffusion, and the cell Peclet number.
Stage 5: Two-dimensional meshes
Introduce two-dimensional cell indexing, face connectivity, and more general mesh data structures.
Stage 6: Incompressible flow
Implement momentum equations and pressure–velocity coupling.
Begin with a well-defined benchmark, such as laminar channel flow or the lid-driven cavity.
Stage 7: Verification and validation
Automate residual monitoring, conservation checks, mesh studies, and comparison with reference solutions.
This progression provides a practical route from a simple numerical program to a more complete CFD solver.
14. Common Mistakes When Building a CFD Solver
Mistake 1: Writing the code before deriving the equations
It is easy to introduce incorrect signs, coefficients, or boundary terms.
Better practice: Derive each discrete equation and document the sign convention before implementation.
Mistake 2: Mixing the physics and the linear solver
A large function that assembles equations, solves them, and writes results is difficult to test.
Better practice: Separate the mesh, physical model, discretization, algebraic solver, and output routines.
Mistake 3: Treating boundary values as cell-centre values
On a cell-centred finite-volume mesh, the first cell centre is not located at the physical boundary.
Better practice: Derive the boundary contribution using the correct centre-to-boundary distance.
Mistake 4: Trusting a single benchmark
A solver can reproduce one simple problem and still contain errors in other equations or boundary conditions.
Better practice: Build a collection of tests covering different physical and numerical features.
Mistake 5: Confusing a small residual with an accurate solution
A linear system can be solved accurately even when the discretized equation does not represent the physical problem adequately.
Better practice: Check the mathematical formulation, discretization error, conservation, and physical reference data.
Mistake 6: Adding complexity too quickly
Implementing turbulence, multiphase physics, and parallel computing before the basic solver is verified makes debugging unnecessarily difficult.
Better practice: Add one capability at a time and preserve the existing tests.
15. Key Takeaways
- A CFD solver is a structured system, not merely a set of equations.
- Physical modelling, discretization, linear algebra, and solver infrastructure should have clear responsibilities.
- A one-dimensional diffusion problem provides a useful first implementation.
- Boundary conditions must be derived consistently with the location of the unknowns.
- The Thomas algorithm efficiently solves tridiagonal systems but is not a general sparse solver.
- Analytical comparisons and conservation checks should be automated.
- A test problem must be chosen to exercise the numerical property being assessed.
- Incompressible flow requires pressure–velocity coupling to enforce continuity.
- The solver should evolve incrementally, with verification at every stage.
- Reproducibility, clear documentation, and automated tests are part of numerical engineering.
16. What’s Next?
The next step is to expand the solver from one-dimensional diffusion toward a reusable finite-volume framework.
A suitable next module would be:
Module 11: C++ Architecture for a Finite-Volume CFD Framework
It would introduce more general mesh representations, scalar and vector fields, boundary-condition interfaces, face-based flux calculations, equation assembly, and automated testing.
The long-term objective is to understand not only how to use professional CFD software, but also how its underlying numerical operations can be represented, implemented, tested, and improved.