对 WatchKit 使用 Objective C++

Using Objective C++ for WatchKit

当我尝试将 Objective C++ 用于我的 WatchKit 扩展时,我收到链接器错误消息,如

Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_WKInterfaceController", referenced from:

我尝试使用单视图应用程序模板创建一个新项目,然后向其中添加一个简单的 WatchKit App 目标。不做任何更改,整个编译都很好,但是如果我将 InterfaceController.m 文件重命名为 InterfaceController.mm,那么即使是那个简单的项目也会出现上述错误。

如何使用 Objective C++ 构建 WatchKit 应用程序扩展?

我在网上或 Apple 的开发论坛上找不到任何关于此的内容,但我终于弄清楚了发生了什么并想出了一个解决方法。

问题似乎是,如果所有源文件都在 C++ 和 Objective C++ 中,则链接器的某种神奇触发器不会发生。解决方案是创建一个包含 WatchKit header 的单个 .m 文件。该文件的内容只需要这个:

#import <WatchKit/WatchKit.h>

将其保存到.m文件中,将其添加到项目中,一切都会变得阳光和彩虹。

我通过 Radar 向 Apple 报告了这个问题并得到了这样的回复:

This issue behaves as intended based on the following:

The difference between the objc and objc++ compiles comes down to objc enabling -fmodules and objc++ not. If you build the objc without -fmodules you get the same link error, and the driver is dropping -fmodules when in C++ mode, leading to the error.

Looks like we get a number of linker option load commands in the object when we use -fmodules, but we don't get them without. Thus, an object with -fmodules can find all of the frameworks it needs on its own, but an object without cannot.

So the problem is simply that objective c++ modules aren't supported, so the project has gone from using modules to not using modules. This means autolinking isn't available, so the project needs to explicitly link against the frameworks that it uses.

对我来说,如果我在 WatchKit 扩展目标的构建设置选项卡中将 Enable Modules (C and Objective-C) 设置为 NO,就会开始发生这种情况。将其设置回 YES 可消除这些错误。

在我的 Swift 项目中集成了一个用 Objective C 编写的第三方框架后,我遇到了同样的问题。我必须创建 Bridging-Header,之后出现相同的错误消息,因为该框架正在引用 WatchKit。我所要做的就是在 Bridging-Header 中导入 WatchKit:

#import <WatchKit/WatchKit.h>