Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an inline variable be changed after initialization in C++17?

My scenario is the following (it worked in clang but not in gcc)

liba.hpp:

inline int MY_GLOBAL = 0;

libother.cpp: (dll)

#include "myliba.hpp"

void myFunc() {
    //
    MYGLOBAL = 28;
}

someexe.cpp:

RunAppThatUsesBothLibAandLibOther();

The problem is that the inline variable was showing 0 in places where I expected 28 because it was alrady modified at run-time. MSVC disagrees with this, but clang does the thing I would expect.

The question is: can inline variables be modified at run-time in my scenario? (I solved the problem by de-inlining the variable.)

like image 860
Germán Diago Avatar asked Dec 05 '19 12:12

Germán Diago


People also ask

Is Constexpr variable inline?

A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.

Can a variable be inline?

A variable declared inline has the same semantics as a function declared inline: it can be defined, identically, in multiple translation units, must be defined in every translation unit in which it is used, and the behavior of the program is as if there was exactly one variable.

Which variable is initialized more than once?

inline variable is initialized more than once.

What is inline variable in Java?

The Inline refactoring lets you reverse the Extract refactoring for a method , constructor, parameter, superclass, anonymous class, and variable. You can inline the pattern variable since the Java 14 version. In this case, all the occurrences will be replaced with old-style cast expression.


1 Answers

Yes, inline variables can be modified after initialization.

However, DLLs are strange things on Windows with MSVC. To a close approximation, each DLL is modelled as its own C++ program, with an entirely independent runtime. Therefore, there is one copy of your inline variable for the main program, and another for the DLL.

like image 161
Anthony Williams Avatar answered Sep 21 '22 18:09

Anthony Williams