Compilation fails calling Cocoa function from C++

2019-08-28 23:59发布

ALL,

I am trying to write following function (function is inlined inside some header):

static bool CocoaFileNameGetSensitivity()
{
    NSNumber id;
    NSURL *url = [NSURL URLWithString:@"/"];
    [url getResourceValue: idforKey: NSURLVolumeSupportsCaseSensitiveNamesKey error: nil];
    return [id boolValue];
}

put that function in the header file and call this function from C++ (not Objective-C) in this way:

/* static */
bool MyClass::IsCaseSensitive()
{
    return CocoaFileNameGetSensitivity();
}

but I'm getting a compiler error:

error: use of undeclared identifier 'CocoaFileNameGetSensitivity'

What am I doing wrong?

Now as a follow-up question - does Objective-C/Cocoa code should be only in .m/.mm files? Or I can write its code in the .h file?

1条回答
爷的心禁止访问
2楼-- · 2019-08-29 00:07

This is actually the core question/insight:

does Objective-C/Cocoa code should be only in .m/.mm files? Or I can write its code in the .h file?

If the header file is #included by a .c or .cpp file, then no, you can't use Objective-C code in it. Avoiding this will probably solve your problem, although it's not 100% clear from what you've posted.

The error error: use of undeclared identifier 'CocoaFileNameGetSensitivity' suggests that perhaps the definition is inside an #if block which isn't compiled in pure C++ mode.

In any case, you will need to make CocoaFileNameGetSensitivity() non-static and move its definition to an .m or .mm file. The declaration can then stay in a shared header, the only thing you need to watch out for is that you probably need to mark it as extern "C" when building with a C++ compiler unless you exclusively use/define the function in Objective-C and C, or Objective-C++ and C++. If you mix (Objective-)C and (Objective-)C++, you will need to ensure the compilers agree on C linkage.

查看更多
登录 后发表回答