Link errors when mixing C++ with C/Objective-C

February 7, 2009
Tags: ,

Twice in the past week, people have asked questions about getting undefined symbol errors when mixing Objective-C and C++. In both cases, this was a result of C++’s name-mangling. Anytime you want to have a single function that is callable from both C++ and Objective-C (or C, for that matter), you need to disable name mangling for that function.

Name Mangling

Normally, in C, the actual symbol name of a function is simply the function’s name with an underscore prepended; that is, int Foo(int i, float f) becomes simply _Foo. Nice and straightforward.

In C++, on the other hand, the exact same function will be named __Z3fooif[1]. At first glance, this seems like unnecessary complication for complication’s sake, but all becomes clear when you bring function overloading into the picture. Since C++ allows multiple functions with the same name to exist, as long as they accept different parameters, it makes sense that the types of the parameters themselves must somehow be encoded in the symbol name.

This is precisely what __Z3fooif is:

  • __Z means “This is a mangled name”.
  • 3 means “The next part of this name is 3 characters long”.
  • foo is the actual name of the function.
  • if represents the types of the parameters (i.e. “int” and “float”)

This allows foo(int,char) to have a different name than foo(int,float) in the binary.

Now What?

So, now that we know why C and C++ encode their function names differently, what can we do about it. The designers of C++ foresaw this situation, after all C++ would have had a long row to hoe were it not compatible with C. They added the extern "C" directive to the language.

There are two ways to apply this directive; either to an entire block of code, or to a single function declaration. Each has it’s advantages and disadvantages:

  • extern "C" int foo(int,float);

    This disables name mangling on this single function

  • extern "C" { ... }

    This disables name mangling on all functions between the curly braces.

Final Gotcha

So, we’re done, right? Not quite. Since C knows nothing of this “extern "C"” business any of the above declarations will fail to compile when passed to a C or Objective-C compiler. They must be conditionally compiled so that only the C++ compiler sees them.

For the single-function version of the declaration, most people define some kind of macro to hide all of this complexity:

#ifdef __cplusplus
#define MY_EXTERN_C extern "C"
#else
#define MY_EXTERN_C extern
#endif

After this is defined, your function declaration becomes:
MY_EXTERN_C int foo(int i, float f);

And, for the block style, just wrap the beginning and end of the block with #ifdef __cplusplus, like so:

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

  1. Note, the exact encoding can vary from compiler to compiler, but the basic principle remains the same []