Thread: extern const for memory allocation?

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    19

    extern const for memory allocation?

    I was reading Microsoft's Inside COM, and I couldn't quite understand one of the comments for a code snippet.

    There are two files of interest.

    File 1 : Iface.h

    Code:
    extern "C"
    {
    extern const IID IID_IX
    }
    File 2 : GUID.cpp

    Code:
    #include <objbase.h>
    
    extern "C"
    {
    extern const IID IID_IX = {0x32bb8320, 0x41b, 0x11cf, ...};
    // The extern is required to allocate memory for C++ constants
    }
    There are two more files associated with this example, one is a file that implements a COM component, and the other is a file that implements a COM client. They both #include "Iface.h", and GUID.cpp are linked to both the component and client when compiled.

    Here, Iface.h is created to "declare" IID_IX variable, and GUIDS.cpp is created to "define" the variable. So I understand why extern key word is used for the variable in Iface.h, but I don't undersatnd why it is used in GUIDS.cpp. So I turned to the comment below the definition of the variable in the GUIDS.cpp file, but I still couldn't make much sense out of it. Particularly, I didn't know what it meant when it stated that extern is requried to allocate memory for C++ constants. I would appreciate for some clarifications. Thank you.
    Last edited by donglee; 11-03-2008 at 01:27 AM.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    The comment is bogus.

    In C++, a const definition at global scope has internal linkage by default - which means it's only available to the translation unit (source file) in which it's defined. Slapping an extern on it gives it external linkage.

    So a better comment would have been:
    // extern needed since const globals have internal linkage

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  2. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  3. "error: incomplete type is not allowed"
    By Fahrenheit in forum C++ Programming
    Replies: 9
    Last Post: 05-10-2005, 09:52 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. vector<>
    By teval in forum C++ Programming
    Replies: 11
    Last Post: 08-18-2003, 03:27 PM

Tags for this Thread