C ++链接器错误类静态constexpr [英] C++ Linker Error With Class static constexpr

查看:119
本文介绍了C ++链接器错误类静态constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 g ++ - 4.6.1编译以下简单程序--std = c ++ 0x

#include <algorithm>

struct S
{
    static constexpr int X = 10;
};

int main()
{
    return std::min(S::X, 0);
};

我得到以下链接器错误:

I get the following linker error:

/tmp/ccBj7UBt.o: In function `main':
scratch.cpp:(.text+0x17): undefined reference to `S::X'
collect2: ld returned 1 exit status



我知道内联定义的静态成员没有定义符号,但我是在(可能有缺陷)的印象,使用 constexpr 告诉编译器始终将符号作为一个表达式;因此,编译器会知道传递对符号 S :: X 的引用是不合法的(出于同样的原因,你不能引用字面值 10 )。

I realize that inline-defined static members do not have symbols defined, but I was under the (probably flawed) impression that using constexpr told the compiler to always treat the symbol as an expression; so, the compiler would know that it is not legal to pass a reference to the symbol S::X (for the same reason you can't take a reference to the literal 10).

然而,如果S被声明为命名空间,即namespace S ,一切都很好。

However if S is declared as namespace, i.e. "namespace S" instead of "struct S", everything links fine.

这是一个 g ++ 错误或者我仍然需要使用一个技巧来解决这个问题恼人?

Is this a g++ bug or do I still have to use a trick to workaround this annoyance?

推荐答案

我不认为这是一个错误。如果将 constexpr 更改为 const ,它仍然会失败,并有完全相同的错误。

I don't think this is a bug. If you change the constexpr to const, it still fails, with the exact same error.

你已经声明了 S :: X ,但没有在任何地方定义,所以没有存储空间。

You've declared S::X, but not defined it anywhere, so there's no storage for it. If you do anything with it that needs to know the address of it then you'll need to define it somewhere also.

例如:

int main() {
      int i = S::X; // fine
      foo<S::X>(); // fine
      const int *p = &S::X; // needs definition
      return std::min(S::X, 0); // needs it also
}

这样做的原因是 constexpr 可以在编译时进行评估,但不是必需的,因此可以同样在运行时发生。它不指示编译器始终将符号视为一个表达式,它暗示如果编译器感觉到这样做是明智和允许的。

The reason for this is that constexpr can be evaluated at compile time, but it's not required to be evaluated as such, and can equally happen at runtime. It doesn't instruct "the compiler to always treat the symbol as an expression", it hints that it would be sensible and permissible to do so if the compiler felt like it.

这篇关于C ++链接器错误类静态constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆