Re: Undefined symbol error for static const char
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
rawhm wrote:
What gives?
$ cat sc.cpp
#include <vector>
class cls {
public:
static const char foo = 100;
};
int main(int argc, char **argv) {
std::vector<char> vect;
vect.resize(10, cls::foo);
return 0;
}
$ g++ sc.cpp
Undefined symbols:
"cls::foo", referenced from:
__ZN3cls3fooE$non_lazy_ptr in ccB49b7c.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
According to ISO/IEC 14882:2009 (draft n2960) Section 9.4.2
[class.static.data]:
2 The declaration of a static data member in its class definition is not a
definition and may be of an incomplete type other than cv-qualified void.
The definition for a static data member shall appear in a namespace scope
enclosing the member???s class definition.
You missed the definition so the linker complains.
3 If a static data member is of const literal type, its declaration in the
class definition can specify a brace-or-equal-initializer in which every
initializer-clause that is an assignment-expression is a constant
expression. A static data member of literal type can be declared in the
class definition with the constexpr specifier; if so, its declaration shall
specify a brace-or-equal-initializer in which every initializer-clause that
is an assignment-expression is a constant expression. [ Note: In both these
cases, the member may appear in constant expressions. ??? end note ] *The
member shall still be defined in a namespace scope if it is used in the
program and the namespace scope definition shall not contain an
initializer.*
You have used the member in the program so a definition is still needed and
the initialization needs to be done in the definition.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEARECAAYFAkrTPygACgkQG6NzcAXitM/RuACdHN42LwvnL9R+NhdEKis7MV3u
tB8An1740a3+k4C4U6vV3Pp9oZPXvDgI
=3mOx
-----END PGP SIGNATURE-----