views:

73

answers:

1

How does the following work?

#include <limits>

int main()
{
  const int* const foo = &std::numeric_limits<int> ::digits;
}

I was under the impression that in order to take an address of a static const-ant member we had to physically define it in some translation unit in order to please the linker. That said, after looking at the preprocessed code for this TU, I couldn't find an external definition for the digits member (or any other relevant members).

I tested this on two compilers (VC++ 10 and g++ 4.2.4) and got identical results from both (i.e., it works). Does the linker auto-magically link against an object file where this stuff is defined, or am I missing something obvious here?

+2  A: 

Well, what makes you think that it is not defined? The very fact that your attempt to take the address succeeded automatically indicates that it is defined somewhere. It is not required to reside in your tranlation unit, of course, so looking through the preprocessor output doesn't make much sense.

AndreyT
Well, two things: 1) I thought that the limits header might be bringing it in to my translation unit. Doesn't seem to be the case. 2) I looked at VS's linker command line and couldn't find any "foreign" object files being implicitly specified.
javery
@javery: Foreign? Why foreign? The definition must be a part of the Standard Library. You *are* linking with standard library, aren't you?
AndreyT
By "foreign" I meant foreign to my own files; that includes the standard library. Sorry for the confusion. :)
javery
@javery: Your code *includes* stanadard header files only. The "meat" of the Standard Library resides in... well... in a *library*, which is normally linked into your project implicitly.
AndreyT
Found it. Like you said, implicitly linked. Was confused because it wasn't explicitly listed as an additional dependency anywhere. Cheers.
javery