Reputation: 679
class test
{
public:
static int i;
int func() {
return i;
}
};
int main()
{
test::i = 20;
}
fails to compile with clang: error: linker command failed with exit code 1 (use -v to see invocation)
.
If I make the static variable inline
, I can define it inside main
. Or if I don't make it inline, I can define it between the class declaration and main()
like so:
class test
{
public:
static int i;
int func() {
return i;
}
};
int test::i = 20;
int main()
{
}
Why does this work but the former doesn't?
Also, why is an int
here needed when it's already been declared as an int
inside test
?
Upvotes: 0
Views: 141
Reputation: 119184
Inside a function, the statement
test::i = 20;
is an expression (not a definition). It stores the value 20 into test::i
. But if test::i
was never defined, you cannot store a value into it.
On the other hand, at namespace scope, when you write
int test::i = 20;
this is a definition of test::i
.
Upvotes: 2