C++20 C++23 模块

在 2024 年的最后一天,再来更新一篇博客,关于 C++ 20,23 新特性模块。

环境配置

我用的环境为 clang 19.1.0,尽量使用官网的包,而不要用 apt 直接安装。

wget https://github.com/llvm/llvm-project/releases/download/llvmorg-19.1.1/LLVM-19.1.1-Linux-X64.tar.xz 

解压。

tar -xf xx.tar.xz -C llvm/

添加环境变量。

vim /etc/profile

添加下面两句。

export LLVM_PATH=you_llvm_path
export PATH=$LLVM_HOME:$PATH

刷新一下

source /etc/profile
source ~/.bashrc

C++模块

xmake 配置

add_rules("mode.debug", "mode.release")

target("stdmodules")
    set_kind("binary")
    add_files("src/*.c")
    add_files("src/*.cpp")
    set_policy("build.c++.modules", true)
    set_runtimes("c++_shared")
target_end()

C++23 Std Modules

这个目前 msvc 支持的比较好,gcc 不支持,clang 支持。

import std;

auto main() -> int
{
    std::cout << "hello world!" << std::<<endl;
    return 0;
}

模块定义

module;

import std;     // 模块 import
#include "test.h"   // 头文件 include

export module module_a;

export

使用 export 来到出模块内的类,函数,变量。

// module_class.cpp
module;

import std;
#include "test.h"

export module module_class;

export class test_class
{
    public:
        test_class() = default;

        auto test_function() -> void
        {
            test_h_test_function();
        }    

    private:
};

函数

// module_function.cpp
module;

import std;

export module module_function;

export auto module_test_function() -> void
{
    std::printf("Hello from test_function!\n");
}

变量

// module_var.cpp
module;

import std;

export module module_var;

export std::string var = "Hello from module_var!";

在另一个模块文件里实现类,函数

// module_test.mxx
export module module_test;

export void test_function_2();

export class test_class_2
{
public:
    void test_function();
};
// module_test.cpp

module module_test;

import std;

void test_function_2()
{
    std::printf("test_function_2\n");
}

void test_class_2::test_function()
{
    std::printf("test_function2\n");
}

import

使用 import 来导入模块。

// main.cpp
import std;
import module_class;
import module_function;
import module_var;
import module_test;

auto main() -> int
{
    test_class test;
    test.test_function();
    module_test_function();
    std::cout<< var << std::endl;
    test_function_2();
    test_class_2 test2;
    test2.test_function();
    return 0;
}