简体   繁体   中英

using c++ in xcode / objective c

So I'm trying to use C++ inside my ios project.

After I make a new project (all default settings, fresh install of xcode), I create a Question.h and a Question.mm file, like this:

Question.h

#include <iostream>
#include <string>
using std::string;

class Question {
public:
   string text;
};


Question.mm

#include "Question.h"

it screams with errors like: Iostream: No such file or directory

using Xcode 3.2.6 with iOS SDK 4.3

What am I doing wrong?

The most likely cause of this is that you're including Question.h in a non-C++ file, for instance perhaps your AppDelegate is am file and you're trying to include Question.h there.

There are two solutions. First, you can make everything Objective-C++ (renaming all.m files to.mm). Historically I've found that to be extremely inconvenient because both Xcode and gdb have always had a lot of trouble with ObjC++ and you can get a lot of confusion (the dreaded "no this pointer" and "unknown language for stack frame" errors in gdb). I haven't done enough work with the latest versions of Xcode and gdb to determine if this is still a problem, but I suspect it is since gdb hasn't gotten a lot of work. Also, ObjC++ is slower to compile.

The other option is to wrap up your C++ into ObjC so that you can include it freely into pure ObjC portions of the code. This is the approach I usually take. ObjC++ is a bit of a mess of a language IMO, and I believe it's better to keep ObjC (.m) and C++ (.cpp) pure and separate with a thin layer of ObjC++ (.mm) to glue them together.

Make sure your main.m file isn't importing your AppDelegate file. It may be using it like this:

NSStringFromClass([AppDelegate class])

but instead you can just do this:

@"AppDelegate"

That solved my problem.

Try renaming Question.mm to Question.cpp as xcode decides which compiler to use based on the extension.

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