lundi 29 novembre 2021

Variable not set inside __attribute__((constructor)) or global static variable reset after __attribute__((constructor)) invoked

I have a std::vector which need to filled with some random values when library is loaded. but I see it is been reset after library is loaded. Is it because of global and static

Library code:

static std::vector<uint8_t> g_randomNr{};


__attribute__((constructor)) void generateRandomNrAtStart(void)
{
    static bool firstLoad = false;
    g_randomNr.clear();
    if (!firstLoad) {
        firstLoad = true;
        std::cout << "Library is loaded and generating first random number ...\n";
    }

    std::cout << "Generating random number ...\n";


    for (int i = 0; i < 20; i++) {
        g_randomNr.push_back(i);
    }

    std::cout << "Random number generated with length of " << g_randomNr.size() << "\n";
}

void getRandomNr(std::vector<uint8_t>& randomNr)
{
    randomNr = g_randomNr;
}

Main code:

int main()
{
    std::vector<uint8_t> randomNr{};
    getRandomNr(randomNr);
    
    std::cout << randomNr.size() << "\n";
    return 0;
}

Output:

Library is loaded and generating first random number ...
Generating random number ...
Random number generated with length of 20
0

In the above output I expect 20 in cout main function but I receive empty vector

Aucun commentaire:

Enregistrer un commentaire