Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are inline static variables unique across modules in visual c++?

c++17 introduce inline (static) variables. It is said that

"The compiler will guarantee that a variable has only one definition and it’s initialised only once through all compilation units."

I am wondering if visual c++ guarantee inline static variable will be unique across multiple modules (dlls and exe).

//cat.h
class __declspec(dllexport) Cat
{
public:
    inline static int var = 0;
};

If cat.h is included in multiple dlls and one exe, is Cat::var unique in the application ?

like image 615
camino Avatar asked Mar 18 '26 06:03

camino


1 Answers

Your question is quite 'open-ended' but, if what you actually want is only one instance, then you should define a macro - say DLLIMPEXP - that is conditionally defined as __declspec(dllexport) in one module (where the class is actually defined, or at least instantiated) and as __declspec(dllimport) in the other two. Then have your header declaration:

//cat.h
class DLLIMPEXP Cat
{
public:
    inline static int var = 0;
};

Note1: I think the class linkage declaration overrides the member's. Note2: It doesn't have to be a DLL that exports; EXEs can export too, and DLLs can import! Note3: As others have said, the C++17 standard does not (cannot) apply across link modules.

like image 152
Adrian Mole Avatar answered Mar 23 '26 16:03

Adrian Mole