简体   繁体   中英

Errors when including Cocoa header

I've been creating a UI toolkit to use on MacOS and Windows, but im currently working and testing the MacOS side of things. Recently, when im compiling my code, using CMake, I get an unreasonable amount of errors from including the Cocoa header. Here is a ghostbin of the errors.

I'm not sure if this is a complete answer to your question, but hopefully it gives you a path forward. Thanks to @uliwitness for mentioning #if __OBJC__ .

So QT5 has a git repo for qmacextras, which combines c++ and objective-c, something I am doing and how I was seeing a bunch of errors when importing <Foundation/Foundation.h> or <Cocoa/Cocoa.h> . Looking at some of their code, I saw this:

// ### remove when merged to QtCore
/*!
 * \macro Q_FORWARD_DECLARE_OBJC_CLASS(classname)
 *
 * Forward-declares an Objective-C class name in a manner such that it can be
 * compiled as either Objective-C or C++.
 *
 * This is primarily intended for use in header files that may be included by
 * both Objective-C and C++ source files.
 */
#ifdef __OBJC__
#define Q_FORWARD_DECLARE_OBJC_CLASS(classname) @class classname
#else
#define Q_FORWARD_DECLARE_OBJC_CLASS(classname) typedef struct objc_object classname
#endif

and

// Put in your header file
Q_FORWARD_DECLARE_OBJC_CLASS(NSData);
Q_FORWARD_DECLARE_OBJC_CLASS(NSImage);
// etc

https://code.qt.io/cgit/qt/qtmacextras.git/tree/examples/macextras/macfunctions?h=5.14

Using this might negate those errors.

You're not really asking a question... but from a casual glance at what little information you provide, it looks like there is ObjC code being run through a non-ObjC compiler.

This usually happens when someone includes an ObjC header from a C or C++ source file. A very common way of causing this is to add a precompiled header to your project that includes Cocoa/Cocoa.h. A precompiled header is used for all C-descended languages you compile, so also for C or C++ files.

To avoid ObjC-specific code from being included in non-ObjC files, wrap it in #if __OBJC__ preprocessor macros. (This also applies to C++ code in your precompiled header, which you'll want to wrap in #if __cplusplus )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM