如何制作自己的 std.core 模块声明?

问题描述

由于模块是在 C++20 中引入到 C++ 中的,但是,std 库本身在 C++23 之前不能作为模块导入。

我想编写像 import std.core; 这样的代码,所以我尝试制作自己的标准库,只需从 std:: 导出一些类和对象。

文件 stdcore.mpp 如下所示:

module;
#include <string>
#include <string_view>

export module stdcore;

// This function will never be used.
// it only exports std::string and std::string_view.
export void __105aw1d065adw__(std::string,std::string_view); 

和 main.cxx:

import stdcore;

int main()
{
    std::string s{"Hello World!"};
    return 0;
}

用这些编译它们:

CXX="clang++ -fmodules-ts -std=c++20 -Wall"
$CXX --precompile -x c++-module stdcore.mpp

一切看起来都不错,但是当我执行此操作时:

$CXX main.cxx -c -fmodule-file=stdcore.pcm

我得到了:

main.cxx:5:2: error: missing '#include <string>'; 'std' must be declared before it is used
        std::string s{"Hello World!"};
        ^
E:\msys64\mingw64\include\c++\10.2.0\string:117:11: note: declaration here is not visible
namespace std _GLIBCXX_VISIBILITY(default)
          ^
1 error generated.

这是什么意思?

解决方法

// This function will never be used.
// it only exports std::string and std::string_view.
export void __105aw1d065adw__(std::string,std::string_view); 

不,您只导出该函数,不导出 std::string/std::string_view

相反,它应该是这样的:

export module stdcore;

export import <string>;
export import <string_view>;
// ...