1

I write a code in C++, and I want to use some of it's methods in my IOS application, so is it possible to (import) C++ library "t.cpp" to IOS application in XCode? if yes what's the simple way to do it?

Hazem Abdullah
  • 1,837
  • 4
  • 23
  • 41

3 Answers3

2

Yes, that will work without error, however you might want to change the Xcode C++ compiler settings (language level and runtime library), depending on the version of iOS you are using.

When it comes to actually using the C++ classes within your Objective-C code, you simply need to rename any files from .m to .mm.

A complication occurs when you want to include the C++ headers in Objective-C headers where both .m and .mm see that Objective-C header file. In this case you might find that you need to change many more files from .m to .mm in order for this to work, but there are ways around this if that becomes too onerous.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • 2
    To avoid the issue of exposing C++ headers to too many other files, I like to write Objective-C classes that wrap corresponding C++ classes or functionality. Then, ideally the C++ headers are only included from the wrapper `.mm` file, and the `.h` file for the Objective-C wrapper class has a nice clean interface with no hint of C++. – Mike Mertsock Jan 15 '14 at 16:00
  • @esker Sounds like a good solution. – trojanfoe Jan 15 '14 at 16:01
0

Just add the file to the project.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

You need to rename a file from .m too .mm only if the translation unit contains a C++ header. Then, the module gets "infected" by C++ and needs to be compiled with the Objective-C++ compiler.

This is only required if any C++ header will be directly or indirectly included/imported from that module. There is no need to rename all files.

Additionally, if this C++ code depends on the C++ standard lib, you need also ensure, that the executable binary links against the C++ standard lib, via setting the appropriate build setting in the executable binary.

For example, in the target build settings of your app, add the following option to Other Linker Flags:
-lc++
e.g.:
OTHER_LDFLAGS = -ObjC -lc++

Caution:

If possible, don't include/import a C++ header in a public Objective-C header, since then all modules will be infected by C++ when they import this Objective-C header and become Objective-C++.

CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67