c++ - clang 编译器挂起 -std=c++17 -O3

标签 c++ string clang++

我正在使用此命令行来编译我的程序。

clang++ -std=c++17 -O3 main.cpp -o main

我在 20 分钟前启动了编译器,但它只是挂起。我终止编译器,并尝试再次编译它,但它仍然挂起。如果我使用完全相同的命令行,但没有 -O3 编译器会立即完成,但使用 -O3 编译器会挂起。

它编译的代码比较简单,没有任何错误。这是怎么回事?

#include <ctime>    // for time()
#include <cstdlib>  // for srand(), rand(), size_t, EXIT_SUCCESS

#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;


int main()
{
    vector<string> messages;
    messages.push_back(string("“Blessed are those who are persecuted because of righteousness, for theirs is the kingdom of heaven.”"));
    messages.push_back(string("“Let the little children come to me, and do not hinder them, for the kingdom of heaven belongs to such as these.”"));

    /* Literally 10000 more quotes from the Bible. */


    srand(time(NULL));

    cout << messages[ rand() % messages.size() ] << endl;

    return EXIT_SUCCESS;
}

这是怎么回事?

最佳答案

如果您想保留程序中的所有字符串(而不是从文件中读取它们),我将替换 std::vector<std::string>const std::vector<std::string_view>或者甚至是 const std::vector<const char*>并用所有字符串初始化它:

#include <ctime>    // for time()
#include <cstdlib>  // for srand(), rand(), size_t, EXIT_SUCCESS

#include <iostream>
#include <string_view>
#include <vector>

int main() {
    const std::vector<std::string_view> messages{
        "“Blessed are those who are persecuted because of righteousness, for theirs is the kingdom of heaven.”",
        "“Let the little children come to me, and do not hinder them, for the kingdom of heaven belongs to such as these.”",
        /* Literally 10000 more quotes from the Bible. */
    };

    srand(time(NULL));

    std::cout << messages[ rand() % messages.size() ] << '\n';
}

我没有足够的耐心等待编译器完成原始代码的编译。以上编译时间约为 1 秒。

注意:有一个 <random> header 可以让您获得比 rand() 更好的伪随机数生成。 。您应该考虑使用它。你的程序的结尾看起来像这样使用:

    std::mt19937 prng(std::random_device{}());
    std::uniform_int_distribution<std::size_t> dist(0, messages.size() - 1);

    std::cout << messages[ dist(prng) ] << '\n';

关于c++ - clang 编译器挂起 -std=c++17 -O3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70490618/

相关文章:

python - 编码字符串

将 stdout 重定向到 Linux 上的文件时,C++ 程序无法生成输出

c++ - 在 VC++ Express 中包含和访问二进制数据的最干净的方法是什么?

string - 如何检查字符串是否为数字 Julia

php - 如何使用 fscanf 读取整行(字符串)?

c++ - 是否已经实现了 C++17 并行算法?

c++ - 是否有编译器警告会在函数返回后捕获代码?

c++ - Apple clang 编译器版本控制架构?

c++ - VS 从 2005 年迁移到 2010 年,LNK1316 : duplicate managed resource name

c++ - 如何在类 .h 文件中使用静态常量来定义数组的长度?