【问题标题】:How can I make my own std.core module declaration?如何制作自己的 std.core 模块声明?
【发布时间】:2021-06-02 21:53:32
【问题描述】:

由于在 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.

这是什么意思?

【问题讨论】:

  • // it only exports std::string and std::string_view.。 IIAC,它只导出函数。我认为您需要类似:export { #include &lt;string&gt; }
  • https://gcc.gnu.org/wiki/cxx-modules 中写着main.cc did not #include &lt;string_view&gt; — it doesn't need to, because it never names that type. The type itself becomes known about due to the exported declaration greeter.
  • “它从不命名该类型” 据我了解,__105aw1d065adw__("hello", "world") 可以。在std::string s 中,您命名该(未导出的)类型。
  • export import &lt;string&gt;; 似乎是你想要的。

标签: c++ c++20 c++-modules


【解决方案1】:
// 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>;
// ...

【讨论】:

  • 了解export import 将导出这些标头定义的所有内容,这将包括所有它们 #include,这一点很重要。这可能意味着会导出大量无关的垃圾,其中一些来自其他标准。
  • clang++ 和 g++ 都不支持这一点,据我所知。他们说*** cannot be imported because it is not known to be a header unit
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
相关资源
最近更新 更多