Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 695
cisgreat Avatar asked Nov 17 '25 23:11

cisgreat


2 Answers

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

like image 71
LaC Avatar answered Nov 19 '25 14:11

LaC


  • 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.

like image 21
Joe Avatar answered Nov 19 '25 12:11

Joe