C++ Modules

 C++ Modules


Modules are a feature introduced in C++20 that provide a new way of organizing and managing code. They offer a more efficient alternative to traditional header files and improve compile times by allowing for faster and more granular compilation. Here's an example demonstrating the usage of 

modules:

Module Interface (example.h):



export module example;


export int add(int a, int b);

Module Implementation (example.cpp):



module example;


export int add(int a, int b) {

    return a + b;

}

Main Program:



import example;

#include <iostream>


int main() {

    int x = 5;

    int y = 10;

    int result = add(x, y);

    std::cout << "Result: " << result << std::endl;


    return 0;

}

In the above code, we have a module interface file example.h that declares a function add. The export keyword is used to indicate that the function and the module itself are available for use by other modules.


The implementation of the module is in the file example.cpp, where the module keyword is used to define the module and the export keyword is used to specify that the add function is exported from the module.


In the main program, we import the example module and use the add function to perform an addition. The module is imported using the import keyword, and the function is used as if it were defined in the same translation unit.


To compile and run this code using modules, you would typically use a C++ compiler that supports modules, such as the latest versions of GCC or Clang, with the appropriate command-line flags.


C++ modules offer a more organized and efficient approach to modularizing code, and they can help improve build times and reduce dependencies on header files.


No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...