Compilation fails calling Cocoa function from C++ [closed]

有些话、适合烂在心里 提交于 2019-12-13 03:58:41

问题


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:


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.



来源:https://stackoverflow.com/questions/57531800/compilation-fails-calling-cocoa-function-from-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!