编译无法从C ++调用Cocoa函数 [英] Compilation fails calling Cocoa function from C++

查看:127
本文介绍了编译无法从C ++调用Cocoa函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部

我正在尝试编写以下函数(函数在某些标头中内联):

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];
}

将该函数放入头文件中,并以这种方式从C ++(不是Objective-C)调用此函数:

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:

错误:使用未声明的标识符'CocoaFileNameGetSensitivity'

error: use of undeclared identifier 'CocoaFileNameGetSensitivity'

我在做什么错了?

现在作为后续问题-Objective-C/Cocoa代码应该只存在于.m/.mm文件中吗?或者我可以将其代码写入.h文件中?

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?

推荐答案

这实际上是核心问题/见解:

This is actually the core question/insight:

Objective-C/Cocoa代码是否仅应位于.m/.mm文件中?或者我可以将其代码写入.h文件中?

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

如果头文件是.c或.cpp文件的#include d,则否,则不能在其中使用Objective-C代码.避免这种情况可能会解决您的问题,尽管您发布的内容尚不清楚100%.

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.

错误error: use of undeclared identifier 'CocoaFileNameGetSensitivity'表明定义可能在#if块中,而该块不是在纯C ++模式下编译的.

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.

在任何情况下,您都需要将CocoaFileNameGetSensitivity()设为非静态,并将其定义移至.m或.mm文件.然后,该声明可以保留在共享头中,您唯一需要注意的是,使用C ++编译器进行构建时,可能需要将其标记为extern "C",除非您在Objective-C和C, Objective-C ++和C ++.如果将(Objective-)C和(Objective-)C ++混合使用,则需要确保编译器就C链接达成共识.

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.

这篇关于编译无法从C ++调用Cocoa函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆