16 How to be a super module: C++ Modules at work

 

This chapter covers

  • Understanding namespaces and how to declare your own
  • Diving deeper into the role of header files
  • Exploring the general concept of C++ modules
  • Understanding modules structure – interface units and implementation units
  • Learning how to write and implement your own modules

Modules are a new feature in C++20 that provide a way to organize code into self-contained units, and are meant to replace traditional header files.

In this chapter, so you can fully understand the concept of modules, we start with some basics: first we explore namespaces, how are they used and how can we create our own namespaces.

Next, we provide a comprehensive overview of organizing C++ code using traditional header files. We explore the role of header files, and teach you how to structure header files effectively, including using include guards and organizing functions, and macros by functionality.

We then move and explore the role modules: You will understand what modules are, and how they are constructed from separate interface and implementation units. We will guide you on how to use the new export and import keywords, and the role each plays in implementing modules in your code. We will also explore some best practice and guidelines. By the end of this chapter, you will be equipped in how to use namespaces, header files and modules effectively, to write clean, efficient and maintainable code.

16.1 You name it! How namespaces can save the day

16.1.1 The anatomy of naming collisions

16.1.2 The global namespace

16.1.3 namespace pollution

16.1.4 Make a name for yourself: Defining a Namespace

16.1.5 Nest assured: Nested Namespaces

16.2 Get a-head of yourself: Header files at work

16.2.1 A Head start – the befits of header files

16.2.2 Head to toe – from source and header files to a working program

16.2.3 Get a head start – Create your own header files

16.2.4 Rolling heads: Why header files are so 2019

16.3 A module of efficiency - Introduction to C++ Modules

16.3.1 A module of success – how do modules really work

16.3.2 Using module partitions

16.3.3 Module implementation units

16.3.4 ‘export’ guidelines

16.3.5 ‘import’ guidelines

16.3.6 Importing module from another module (module dependencies)

16.3.7 Modules and namespaces

16.3.8 The rules of modules and namespaces

16.3.9 Common Pitfalls and mistakes when using modules

16.4 Final exercise

16.5 summary