CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2006
    Posts
    384

    Use of extern "C" with global variables

    Hi,

    Over the years had thought that extern "C" was used to prevent C++ compilers from mangling function names - to allow calls from C code to C++ code. Name mangling was introduced in C++ compilers for the purpose of support for function over-riding.

    However, I have come across code where extern "C" has been used to declare global variables in a file. I thought global variables had nothing to do with name mangling - besides I am used to seeing only the extern keyword to declare global variables.

    Can you please let me understand the reason why extern "C" would need to be used with global data variables too ?

  2. #2
    Join Date
    Aug 2004
    Location
    Bucharest, Romania... sometimes
    Posts
    1,039

    Re: Use of extern "C" with global variables

    Variables, global or not, can be mangled too... think of those belonging to a namespace! When you use extern keyword, the variable is being shared across translation units. When you use __dllspec(dllexport), it is being exported by the module. When mixed C / C++ implementations, extern "C" would be required.
    Best regards,
    Bogdan Apostol
    ESRI Developer Network

    Compilers demystified - Function pointers in Visual Basic 6.0
    Enables the use of function pointers in VB6 and shows how to embed native code in a VB application.

    Customize your R2H
    The unofficial board dedicated to ASUS R2H UMPC owners.

  3. #3
    Join Date
    Jan 2006
    Posts
    384

    Re: Use of extern "C" with global variables

    Thank you Bornish. The concept of namespaces also introduces name mangling - missed that point.

  4. #4
    Join Date
    Aug 2004
    Location
    Bucharest, Romania... sometimes
    Posts
    1,039

    Re: Use of extern "C" with global variables

    You're most welcome!
    Bogdan Apostol
    ESRI Developer Network

    Compilers demystified - Function pointers in Visual Basic 6.0
    Enables the use of function pointers in VB6 and shows how to embed native code in a VB application.

    Customize your R2H
    The unofficial board dedicated to ASUS R2H UMPC owners.

  5. #5
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Use of extern "C" with global variables

    It is to signal the compiler that the symbol (the variable) has external linkage, that it may be being used in other compilation units.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured