Here is a header file containing an inline variable:
// inline.hpp
#pragma once
#include <iostream>
struct Test {
~Test() { std::cout << "deleted" << std::endl; }
};
inline const Test test;
...included into two .cpp
files:
// usage.cpp
#include "inline.hpp"
// main.cpp
#include "inline.hpp"
auto main() -> int { return 0; }
This program prints "deleted" twice which is unexpected. I thought there was only a single instance of every inline variable, so I was expecting only one "deleted".
Is this a bug of the compiler? Or did I do something wrong?
The code is compiled with VS2017.
As far as I can tell, yes. GCC and Clang, (as well as VS2019 according to comments) print "deleted" only once.
A non-volatile const inline variable in namespace scope has external linkage. The behaviour that you describe appears to imply internal linkage, which is wrong behaviour from the compiler.
For completeness, the relevant standard rules (from latest draft, emphasis added by me, bracketed emphasised parts added by me):