次のコードを使用すると、リンカ エラーに困惑します。
// static_const.cpp -- complete code
#include <vector>
struct Elem {
static const int value = 0;
};
int main(int argc, char *argv[]) {
std::vector<Elem> v(1);
std::vector<Elem>::iterator it;
it = v.begin();
return it->value;
}
ただし、これはリンク時に失敗します。何らかの方法で、静的 const の「値」のシンボルが必要です。
$ g++ static_const.cpp
/tmp/ccZTyfe7.o: In function `main':
static_const.cpp:(.text+0x8e): undefined reference to `Elem::value'
collect2: ld returned 1 exit status
ところで、これは -O1 以上で問題なくコンパイルされます。しかし、より複雑なケースではまだ失敗します。gcc バージョン 4.4.4 20100726 (Red Hat 4.4.4-13) を使用しています。
私のコードで何が間違っているのでしょうか?