4

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?

4

1 回答 1

0

这听起来像是一个完全损坏的工具链,尤其是因为您甚至没有直接包含<limits>自己。显然,Visual Studio 2015 的“非扩展”模式并没有像“向 C++ 中添加很多东西”模式那样得到那么多的测试。

FWIW,你的代码很好。

在 MS Connect 上提出错误。

幸运的是,您已经有了解决方法。

于 2016-04-02T01:05:28.557 回答