global constructor initialization warning

Mohammad Mohsin Siddiqui 175 Reputation points
2024-03-20T06:43:47.97+00:00

MSVC compiler not generating warning for global constructor initialization. We want to disable global constructor initialization before main. So basically lets say I have a UDT and I want to make sure that this type/class does not gets initiated before main, what should I do using. Basically we want to have some warning for below code usage.

class MyClass {

public:

MyClass ()
    {
        number=100;
    }

private:

int  number;
};

MyClass x;  //this should generate global constructor initialization warning . 

int main()
{

return 0;
}

We tried to compile above code using MSVC compiler and with "/Wall " flag but it did not generate any warning.

if we compile same code with Clang with “-Wglobal-constructors” compiler option, it gives us below warning.

/Users/mohsin.siddiqui/Workspace/source.cpp:21:9: warning: declaration requires a global constructor [-Wglobal-constructors] MyClass x;

Does this means that MSVC does not even have this warning supported ?

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,888 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,636 questions
{count} votes

Accepted answer
  1. David Lowndes 2,510 Reputation points MVP
    2024-03-20T10:12:09.7466667+00:00

    In your Visual Studio project, if you enable clang-tidy checking in the code analysis settings you should get this warning:
    warning G344A74EF: declaration requires a global constructor [clang-diagnostic-global-constructors]

    User's image

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful