I have one header and two source files.
main.cpp:
#include <iostream>
#include "constant.h"
int main() {
std::cout << test.at("Hello") << std::endl;
}
constant.h:
#ifndef CONSTANT_H
#define CONSTANT_H
#include <string>
#include <unordered_map>
extern std::unordered_map<std::string, int> const test;
#endif
constant.cpp:
#include "constant.h"
std::unordered_map<std::string, int> const test = {
{"Hello", 1},
{"World", 2}
};
When I compile with Visual C++(Visual Studio 2015 Update 1) I get lots of multiple definition linker errors.
EDIT: it only happens when the /Za(Disable Language Extensions) switch is enabled
All of them seem to originate from the <limits> header.
Here are the first few errors(sorry for german compiler output):
1>constant.obj : error LNK2005: "public: static bool const std::numeric_limits<unsigned char>::is_signed" (?is_signed@?$numeric_limits@E@std@@2_NB) ist bereits in main.obj definiert.
1>constant.obj : error LNK2005: "public: static int const std::numeric_limits<unsigned char>::digits" (?digits@?$numeric_limits@E@std@@2HB) ist bereits in main.obj definiert.
1>constant.obj : error LNK2005: "public: static int const std::numeric_limits<unsigned char>::digits10" (?digits10@?$numeric_limits@E@std@@2HB) ist bereits in main.obj definiert.
1>constant.obj : error LNK2005: "public: static bool const std::numeric_limits<short>::is_signed" (?is_signed@?$numeric_limits@F@std@@2_NB) ist bereits in main.obj definiert.
1>constant.obj : error LNK2005: "public: static int const std::numeric_limits<short>::digits" (?digits@?$numeric_limits@F@std@@2HB) ist bereits in main.obj definiert.
1>constant.obj : error LNK2005: "public: static int const std::numeric_limits<short>::digits10" (?digits10@?$numeric_limits@F@std@@2HB) ist bereits in main.obj definiert.
However, when I compile the same code with Clang/C2 or with g++ or clang++ on linux, I don't get any linker errors.
Does this program violate the ODR and is Visual C++ correct in rejecting it?