• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: why use extern "C"
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: why use extern "C"


  • Subject: Re: why use extern "C"
  • From: Uli Kusterer <email@hidden>
  • Date: Sun, 12 Mar 2017 13:19:31 +0100

On 7 Mar 2017, at 17:45, bigpig <email@hidden> wrote:
> I see some code like this in iOS project:
>
> #ifdef __cplusplus
> extern "C" {
> #endif

Others have mentioned what this code does, but I think it'd be useful to provide some background why this is needed:

In C, functions are distinguished by name. A function named "min" must take the same parameter types wherever it occurs in your program. There may be no two functions with the same name.

In C++, both the name and the parameter types are used to distinguish between two functions. You may have several functions that have the same name, as long as they take a different number of parameters, or take parameters of different types.

However, under the hood, both C++ and C are compiled to machine code. And that only supports a single function with the same name, and doesn't know about parameter types. So what the C++ developers did to make this behaviour possible is that they changed the names for functions. Every function contains a few characters at the end of its name that indicate what types its parameters have.

That way, the two functions actually have a different name to the assembler, but there is a rule the programming language can use to generate the actual function name based on the name and types it knows. This is what is called "name mangling."

However, this is something only C++ does, and only C++ knows about. Name mangling is fine when you are only using C++, but when you want to make C++ functions available to C code, you need to tell your C++ compiler not to mangle the function names so C will be able to call them. This is what 'extern "C"' does. It turns off name mangling for the functions between the "{" and "}".

Cheers,
-- Uli Kusterer
"The Witnesses of TeachText are everywhere..."
http://www.zathras.de


_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden


References: 
 >why use extern "C" (From: bigpig <email@hidden>)

  • Prev by Date: Printing questions
  • Next by Date: Re: Unicode filenames with Apple File System and UIManagedDocument
  • Previous by thread: Re: why use extern "C"
  • Next by thread: needsDisplay and subviews
  • Index(es):
    • Date
    • Thread