Bug 26597 - static const class member, ?:, undefined reference
Summary: static const class member, ?:, undefined reference
Status: RESOLVED DUPLICATE of bug 23370
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.1.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2006-03-07 19:18 UTC by Elmar Teufl
Modified: 2006-03-07 19:47 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Elmar Teufl 2006-03-07 19:18:26 UTC
Consider the following code:
=== bug.cpp ===
struct Test {
 static const int number=5;
 int test(const int n);
};

int Test::test(const int n)
{
 int max = number > n ? number : n;
 return max;
}

int main()
{
 Test t;
 t.test(6);
 return 0;
}
============
I get the following linker error:
/tmp/ccWCtyqx.o(.text+0x18): In function `Test::test(int)':
: undefined reference to `Test::number'
collect2: ld returned 1 exit status

I have tested g++ 3.3.5, 4.0.2, and 4.1.0. With g++ 4.* and -O2 the error disappears. Also if one replaces the ? : by an if statement, the error disappears. Of course, an additional "extern const int Test::number;" also solves the problem.

Environment: i386-linux (Debian GNU/Linux)
Releases: 3.3.5, 4.0.2, 4.1.0
How-To-Repeat: g++ -o bug bug.cpp

Best regards,
Elmar
Comment 1 Andrew Pinski 2006-03-07 19:47:37 UTC
Here is the relevant section of the standard (TC1, 
section 9.4.2, paragraph 4):

  If a 'static' data member is of 'const' integral or 'const' enumeral type,
  its declaration in the class definition can specify a 'constant-initializer'
  which shall be an integral constant expression (5.19).  In that case, the
  member can appear in integral constant expressions.  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'.

*** This bug has been marked as a duplicate of 23370 ***