How to include C code in an Xcode project


Apple tells us that 'Objective-C is a superset of the C language', but what does this mean when it comes to including C code in Xcode projects? This post begins to explore that question.

C primitive types

It is likely that you already use C primitives in your code, i.e. int, double and float, to denote number types. In which case you are already mixing C with Objective-C.

C arrays

You could if you wished use int arrays and char arrays as well, for example:

int arr[] = {1,2,3,4,5};
 
    NSLog(@"%i",arr[3]);

Although most likely you are using NSArray and NSMutableArray.

C functions

To take a step further, let's grab a C function from the University of Strathclyde site and insert it into our code:

double power(double val, unsigned pow)
{   double ret_val = 1.0;
    unsigned i;
 
    for(i = 0; i < pow; i++)
        ret_val *= val;
 
    return(ret_val);
}

It's the equivalent of writing:

-(double)valueOf:(double)val toThePower:(unsigned)pow {
 
    double ret_val = 1.0;
    unsigned i;
 
    for(i = 0; i < pow; i++)
        ret_val *= val;
 
    return(ret_val); }


and as with an Objective-C method, the C function goes in the body of the implementation file and can be called from within a method.

So in viewDidLoad, we could call the C function by writing:

double result1 = power(6, 2);

just as we'd write this in Objective-C:

double result2 = [self valueOf:6 toThePower:2];

Typedef structs

You can also create structs using typedef.

typedef struct {
    int i;
    float f;
} MyNewStruct;

Again, the struct code is placed within the body of implementation file and we can make use of the code like this:

 MyNewStruct aStruct;
    aStruct.i = 47;
    aStruct.f = 3.14;

Further reading

Write Objective-C code, Apple

Programming with Objective-C: Values and Collections, Apple

Introduction to C++ for iOS Developers: Part 1, Matt Galloway

Note: In OS X you denote an implementation file that contains Objective-C with the .m extension and you save your implementation file with the extension .mm when it contains Objective-C, C and C++.




Endorse on Coderwall

Comments