cisgreat
cisgreat

Reputation: 75

How to add C/C++ functions to Objective-C code (iphone related)

I added .h/.cpp files with C functions to my Xcode project. How would I call a C function in an objective-C function?

When I included the C file (#import "example.h") in the app delegate header file it exploded with errors (could be that it treated the cpp file as objective-c) even though it compiles fine without being included/imported.

Thanks

Edit: Renaming all the files from m to mm fixed the issue. However I am getting a linker error when building (ld: duplicate symbol)... Better research this first. Thanks again all.

Upvotes: 3

Views: 6202

Answers (3)

Joe
Joe

Reputation: 57179

  • To use plain C in Objective-C just include the header/source file as usual and call the functions. The C files can use the standard extension .h and .c. A lot of libraries are already used this way such as libxml and sqlite.

  • To write C code that can use Objective-C (access FoundationFramework) it will need to be placed in a .m file. A .m file can contain all C functions just like the main.m generated with new projects.

  • To call C++ code the C++ can be in a .cpp (or other valid extension) but your Objective-C file needs the extension .mm to call it, and once again simply include the header file. And to use Objective-C inside of a C++ class it will need the .mm extension.

Upvotes: 7

Kristopher Johnson
Kristopher Johnson

Reputation: 82565

C functions should be callable without doing anything special. Objective-C is a superset of C.

If the headers include C++ stuff, then you need to compile your files as Objective-C++ instead of Objective-C. To do this, just change the file extensions from .m to .mm.

Upvotes: 2

LaC
LaC

Reputation: 12824

If you want to use C++ with your Objective-C module, change the file extension from .m to .mm.

Upvotes: 7

Related Questions