Undefined reference to static const int

2019-01-04 01:00发布

I ran into an interesting issue today. Consider this simple example:

template <typename T>
void foo(const T & a) { /* code */ }

// This would also fail
// void foo(const int & a) { /* code */ }

class Bar
{
public:
   static const int kConst = 1;
   void func()
   {
      foo(kConst);           // This is the important line
   }
};

int main()
{
   Bar b;
   b.func();
}

When compiling I get an error:

Undefined reference to 'Bar::kConst'

Now, I'm pretty sure that this is because the static const int is not defined anywhere, which is intentional because according to my understanding the compiler should be able to make the replacement at compile-time and not need a definition. However, since the function takes a const int & parameter, it seems to be not making the substitution, and instead preferring a reference. I can resolve this issue by making the following change:

foo(static_cast<int>(kConst));

I believe this is now forcing the compiler to make a temporary int, and then pass a reference to that, which it can successfully do at compile time.

I was wondering if this was intentional, or am I expecting too much from gcc to be able to handle this case? Or is this something I shouldn't be doing for some reason?

标签: c++ gcc
8条回答
何必那么认真
2楼-- · 2019-01-04 01:55

I experienced the same problem as mentioned by Cloderic (static const in a ternary operator: r = s ? kConst1 : kConst2), but it only complained after turning off compiler optimization (-O0 instead of -Os). Happened on gcc-none-eabi 4.8.5.

查看更多
聊天终结者
3楼-- · 2019-01-04 02:00

g++ version 4.3.4 accepts this code (see this link). But g++ version 4.4.0 rejects it.

查看更多
登录 后发表回答