Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSVC: static struct std::atomic<bool> Test::g_test has different type

I had the following warning with my Visual Studio 17 (2022) project, and I could reduce it to the following:

test1.cpp

#include <atomic>
#include "test.h"

int main() {
    Test::g_test = true;
}

test2.cpp

#include <atomic>

struct A {
    std::atomic<bool> m_test = false;
};

#include "test.h"

void a() {
    Test::g_test = true;
}

test.h

#pragma once

struct Test {
    static inline std::atomic<bool> g_test = false;
};

Result:

1>------ Build started: Project: ConsoleApplication1, Configuration: Release x64 ------
1>test1.cpp
1>test2.cpp
1>LINK : warning C4744: 'static struct std::atomic<bool> Test::g_test' has different type in 'c:\consoleapplication1\test2.cpp' and 'c:\consoleapplication1\test1.cpp': '__declspec(align(1)) struct (1 bytes)' and 'struct (1 bytes)'

Am I violating some C++ rules? Is it an MSVC bug? What would be the best fix/workaround?

like image 505
Paul Avatar asked Sep 19 '25 13:09

Paul


1 Answers

It's a compiler bug. See https://github.com/microsoft/STL/issues/3241 and https://developercommunity.visualstudio.com/t/10207002.

Reduced from STL bug report https://github.com/microsoft/STL/issues/3241, this seems to actually be a compiler issue.

Create file a.cpp:

template <class T> struct atomic { alignas(sizeof(T)) T x; };

struct S0 { static inline atomic<bool> z; };

int main() { (void) S0::z; }

and file b.cpp:

template <class T> struct atomic { alignas(sizeof(T)) T x; };

struct S1 { atomic<bool> y; };

struct S0 { static inline atomic<bool> z; };

void f() { (void) S0::z; }

then compile with “cl /nologo /std:c++17 /GL a.cpp b.cpp” which emits:

a.cpp
b.cpp
warning C4744: 'static struct atomic<bool> S0::z' has different type in 'b.cpp' and 'a.cpp': '__declspec(align(1)) struct (1 bytes)' and 'struct (1 bytes)'
Generating code
Finished generating code

Notably, no warning is emitted if the declarations of S1 and S0 are reordered in b.cpp.

like image 111
Paul Avatar answered Sep 22 '25 04:09

Paul