都0202年了,还不把C++20的环境搞起来?

300 阅读1分钟

Linux

系统环境:deepin 15.11(ubuntu也是可以的)

GCC版本:GCC 10.2

1. 下载源码

首先我们进入GCC官网,找到下面这个看上去最新的版本。

接着我们找到镜像站。

然后发现没有中国的,不要紧,去俄国的就行。

找到gcc-10.2.0.tar.gz,点击下载,然后解压就好了,镜像地址在这里

2. 编译源码

到此我们得到了gcc-10.2.0文件夹,我这里假设你将它放进了家目录。我们再创建一个objdir文件夹,用于存放编译源码得到的文件。

$ mkdir ~/objdir
$ cd ~/objdir
$ ~/gcc-10.2.0/configure --disable-multilib

接着configure脚本会提示你让你去一个ftp上下载相应的依赖(GMPMPFRMPC),下载最新版并解压到gcc-10.2.0目录下。

重新执行configure脚本,等待编译完成后,使用make构建。

$ ~/gcc-10.2.0/configure --disable-multilib
$ make

3. 环境配置

执行make install,安装后,头文件在/usr/local/include,可执行文件在/usr/local/bin,库文件在/usr/local/lib

$ sudo make install

执行gcc --version,输出如下即安装成功。

gcc (GCC) 10.2.0
Copyright © 2020 Free Software Foundation, Inc.

我们去cppreference找一段C++20标准的代码编译试试!

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <span>
 
template<class T, std::size_t N> [[nodiscard]]
constexpr auto slide(std::span<T,N> s, std::size_t offset, std::size_t width) {
    return s.subspan(offset, offset + width <= s.size() ? width : 0U);
}
 
template<class T, std::size_t N, std::size_t M> [[nodiscard]]
constexpr bool starts_with(std::span<T,N> data, std::span<T,M> prefix) {
    return data.size() >= prefix.size() 
        && std::equal(prefix.begin(), prefix.end(), data.begin());
}
 
template<class T, std::size_t N, std::size_t M> [[nodiscard]]
constexpr bool ends_with(std::span<T,N> data, std::span<T,M> suffix) {
    return data.size() >= suffix.size() 
        && std::equal(data.end() - suffix.size(), data.end(), 
                      suffix.end() - suffix.size());
}
 
template<class T, std::size_t N, std::size_t M> [[nodiscard]]
constexpr bool contains(std::span<T,N> span, std::span<T,M> sub) {
    return std::search(span.begin(), span.end(), sub.begin(), sub.end())
        != span.end();
}
 
void print(const auto& seq) {
    for (const auto& elem : seq) std::cout << elem << ' ';
    std::cout << '\n';
}
 
int main()
{
    constexpr int a[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
    constexpr int b[] { 8, 7, 6 };
 
    for (std::size_t offset{}; ; ++offset) {
        constexpr std::size_t width{6};
        auto s = slide(std::span{a}, offset, width);
        if (s.empty())
            break;
        print(s);
    }
 
    static_assert(starts_with(std::span{a}, std::span{a,4})
        && starts_with(std::span{a+1, 4}, std::span{a+1,3})
        && !starts_with(std::span{a}, std::span{b})
        && !starts_with(std::span{a,8}, std::span{a+1,3})
        && ends_with(std::span{a}, std::span{a+6,3})
        && !ends_with(std::span{a}, std::span{a+6,2})
        && contains(std::span{a}, std::span{a+1,4})
        && !contains(std::span{a,8}, std::span{a,9}));
}

编译命令&执行结果如下。

$ g++ test20.cc --std=c++20
$ ./a.out
0 1 2 3 4 5 
1 2 3 4 5 6 
2 3 4 5 6 7 
3 4 5 6 7 8

至此我们C++20的环境就安装成功了!

Windows

系统环境:Windows10 专业版

GCC版本:GCC 10.2

进入WinLibs,找到这里。

根据自己的系统版本下载就好了,下载后解压,然后将mingw64\bin\添加到Path即可,超简单。