缺少Apple Clang 13 C++20模块支持 [英] Apple Clang 13 C++20 Module Support Missing

查看:0
本文介绍了缺少Apple Clang 13 C++20模块支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据official documentation,Clang 13通过使用-fmodules命令行参数支持C++20模块。

我甚至无法在基于Intel或M1的Mac上使用Clang 13(MacOS蒙特雷)编译基本模块。

假定文件module.cpp的文本内容如下:

export module a;

export int f(int a, int b) {
    return a + b;
}

运行以下程序:

$ clang++ --version
Apple clang version 13.0.0 (clang-1300.0.29.3)
Target: x86_64-apple-darwin21.1.0

$ clang++ -std=c++20 -stdlib=libc++ -fmodules -fbuiltin-module-map -c module.cpp 
module.cpp:1:8: error: expected template
export module a;
       ^
module.cpp:1:8: error: unknown type name 'module'
module.cpp:3:8: error: expected template
export int f(int a, int b) {
       ^
3 errors generated.

在ARM M1芯片上测试,结果相同:

$ clang++ --version
Apple clang version 13.0.0 (clang-1300.0.29.3)
Target: arm64-apple-darwin21.1.0

有没有其他方法让模块正常工作,或者Apple Clang 13是否有一些未记录的C++20模块限制?

注意:使用实验-fmodules-ts标志编译有效。

推荐答案

原因

感谢您的评论-上面的错误表明Clang版本是在没有模块支持的情况下构建的。这就是Xcode附带的功能,即在终端中运行xcode-select --install

解决方案

正如建议的那样,解决方案是通过安装Clang通过自制软件进行安装,具体操作如下(在MacOS蒙特雷上测试):

brew install llvm

Clang安装到/opt/homebrew/opt/llvm/bin/clang++。确认正在运行的版本,如下所示:

% /opt/homebrew/opt/llvm/bin/clang++ --version
Homebrew clang version 13.0.0
Target: arm64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /opt/homebrew/opt/llvm/bin

与Xcode系统范围默认版本不同的版本:

% clang++ --version
Apple clang version 13.0.0 (clang-1300.0.29.3)
Target: arm64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

工作示例

查看基于@alexpter发布的repo的工作示例的步骤:

main.cpp

import <iostream>;
import mathlib;

using namespace std;

int main() {
    cout << "Modules, baby!" << endl;
    cout << "2 plus 3 makes " << add(2, 3) << " says module 'mathlib'" << endl;
}

mathlib.cpp

export module mathlib;

export int add(int a, int b)
{
    return a + b;
}

在与上述文件位于同一目录的终端中运行生成:

/opt/homebrew/opt/llvm/bin/clang++ -std=c++20 -c -Xclang -emit-module-interface mathlib.cpp -o mathlib.pcm
/opt/homebrew/opt/llvm/bin/clang++ -std=c++20 -fmodules -c -fprebuilt-module-path=. main.cpp -o main.o
/opt/homebrew/opt/llvm/bin/clang++ -std=c++2a -fmodules -o main main.o *.pcm

测试基于模块的可执行文件:

./main

预期输出:

Modules, baby!
2 plus 3 makes 5 says module 'mathlib'

这篇关于缺少Apple Clang 13 C++20模块支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆