clang++ compiler is hanging with -std=c++17 -O3

Viewed 119

I am using this command line to compile my program.

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

I have started the compiler 20 minutes ago, and it is just hanging. I terminate the compiler, and try to compile it again and it is still hanging. If I use the exact same command line, but without the -O3 the compiler completes instantly, but with the -O3 it is hanging.

The code that it is compiling is relatively simple, without any errors. What is going on?

#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;
}

What is going on?

1 Answers

If you want to keep all the strings in the program (instead of reading them from a file) I would replace the std::vector<std::string> with a const std::vector<std::string_view> or maybe even a const std::vector<const char*> and initialize it with all the strings:

#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';
}

I wasn't patient enough to wait for the compiler to finish compiling your original code. The above compiled in ~1 second.

Note: There's a <random> header which gives you access to much better pseudo random number generation than rand(). You should look into using that instead. The end of your program would look like something like this using that:

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

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