Question

I created a function in a Cocoa Framework that I want to export. This function is implement in ObjectiveC++, and the name mangling of C++ is driving me nuts.

I already declared the function within an extern "C" block, to no avail.

This is my header file in the framework:

#import <Cocoa/Cocoa.h>

extern "C"{
    void display(NSString *text);
}

@interface Display : NSObject

@end

and this is the .mm file:

#import "Display.h"

#include <string>
#include <iostream>

using namespace std;

void display(NSString *text){
    cout << [text cStringUsingEncoding:NSUTF8StringEncoding] << endl;
}

@implementation Display


@end

It compiles fine, without any errors.

On the client side, I added the framework, imported the exposed header and tried to call the function:

display(@"Hola");

Here I get a warning complaining that "implicit declaration of function display is invalid in C99".

To add insult to injury, in the exposed header file I get an error (that doesn't show up in the framework project), in the extern "C" line:

"expected identifier or ("

What else is necessary to get this going?

Was it helpful?

Solution

You need to add extern "C" to the function implementation as well as the declaration. If the implementation of the function is in a .mm (Objective-C++) file, it will be compiled as Objective-C++, with name mangling. It doesn't matter that you happen to have an extern "C" declaration for a function with the same name. They are still seen as two different things.

So wrap your implementation in extern "C" as well to remove the name mangling for the function implementation:

extern "C" void display(NSString *text) {

}

Or:

extern "C" {
    void display(NSString *text) {

    }
}

Also, if you want your header to be usable by C code, you will need to add an #ifdef to only use extern when compiling as C++. extern is not a valid keyword in C:

#ifdef __cplusplus
    extern "C" {
#endif
void display(NSString *text);
#ifdef __cplusplus
    }
#endif

See Combining C++ and C - how does #ifdef __cplusplus work? for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top