Re: Undefined symbol error for static const char
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
Adding an intializer to a static const member _declaration_ does not
turn it into a _definition_. A separate _definition_ of that static
member is still required, if the member is "used" in the code. What
constitutes a "use" of such a member changed from the "original" C++
specification (1998) to the later ones.
In the original C++ standard, the way you are using 'cls::foo' in your
code does qualify as a "use", so you have to _define_ your 'cls::foo'
separately at namespace scope
const char cls::foo;
If your GCC version adheres to that original standard, that would be the
reason for that legitimate linker error.
In the updated C++ standard the definition of "use" for integral
constants was changed considerably. I'm not sure whether 'cls::foo' is
"used" according to the new definition (can't check right now).
Anyway, what version of GCC are you using?
--
Best regards,
Andrey Tarasevich