Skip to main content

Section 16.13 Using Modules

Things are even simpler if we use C++ modules. In that case, we don’t need to make separate .h and .cpp files. And the only thing we generally need to export other than the module itself is the class we are defining.
...
export module Point;
export class Point {
  ...

Note 16.13.1.

We do not have to export the member functions of the class. Exporting the class makes them available.
We may still wish to place the function definitions outside of the class. That way, the class definition has the minimal amount of code necessary and sticks to just what an β€œoutside user” of the code should care about. The implementation details are there, but out of the way. But all of this code can go into a single file like Point.cxx:
Listing 16.13.1. Point.cxx
// Start global module fragment
module;

// All includes go here
#include <cmath>

// Start module, declare its name and make available outside this module
export module Point;

/**
 * @brief Represents a point in 2D space.
 *
 */
export class Point {
public:
  /**
   * @brief Construct a new Point object
   *
   * @param x starting x coordinate
   * @param y starting y coordinate
   */
  Point(double x, double y);

  /**
   * @brief Get the x coordinate of the point
   *
   * @return double x coordinate
   */
  double getX();

private:
  double m_x;
  double m_y;
};

// Implementations
Point::Point(double x, double y)
{
  m_x = x;
  m_y = y;
}

double Point::getX()
{
  return m_x;
}

Note 16.13.2.

It is still possible to separate the module into an interface file and an implementation file if we want to do so. However, with modules, there is not the same technical need to do so.
With that file defined, we are ready to import the library and build the code:
Listing 16.13.2.
$ g++ -std=c++20 Point.cxx main.cpp -o program.exe
You have attempted of activities on this page.