Declare external functions in A Cocoa / Obj-C project
Okay, like that. I ended up with a basic Cocoa tool that calculates the mean absolute deviation of random integers (just like the tutorial project).
I moved the calculation into a function called "findMeanAbsoluteDeviation ()". It takes NSMutableArray objects from NSNumber to compute the preliminary form. Anyway. So this works fine and dandy when I declare it in the same ".m" file as in my other code.
#import <Foundation/Foundation.h>
float findMeanAbsoluteDeviation(NSMutableArray * array);
int main (int argc, const char * argv[]) {
...generate random integers, execute function...
meanAbsoluteDeviation = findMeanAbsoluteDeviation(numArray);
}
float findMeanAbsoluteDeviation(NSMutableArray * array) {
...mean absolute deviation maths...
}
and it works great. Now I would like to move the function to an external file. I created a subclass of NSObject called insane. I moved the function to my insane "mad.m", I read and then reformatted the declaration to look like
-(float)findMeanAbsoluteDeviation:(NSMutableArray *)array {
...code...
}
and in my "mad.h" file.
@interface mad : NSObject {
}
- (float)findMeanAbsoluteDeviation:(NSMutableArray *)array;
@end
seems awesome. Right? all i have to do is add ...
#import "mad.m"
at the top of my "main.m" file and use the function as usual. Well it looks like it doesn't compile correctly.
ld: duplicate symbol .objc_class_name_mad in ------standardDeviation.build/Debug/standardDeviation.build/Objects-normal/i386/mad.o and ------standardDeviation.build/Debug/standardDeviation.build/Objects-normal/i386/standardDeviation.o
"------" omitted for length
Command /Developer/usr/bin/gcc-4.0 failed with error code 1
Any ideas? Thanks for your help!
a source to share
You want #import "mad.h"
, not #import "mad.m"
, otherwise the implementation of the class is evaluated twice, hence you see the error.
Several stylistic points:
- Unless you are using object instance variables for anything, you usually write a class method (+) rather than an instance method (-).
- There is no problem declaring a C function prototype in an Objective-C header file if the class interface doesn't make sense for what you are doing. See
NSGeometry.h
for some examples. - Unless you're mutating an array in a function or method, don't use a mutable array parameter.
- Consider using the standard Cocoa naming conventions for classes, methods, and functions.
For instance:
@interface MEMeanAbsoluteDeviation : NSObject {
}
+ (float)meanAbsoluteDeviation:(NSArray *)array;
or simply:
float MEMeanAbsoluteDeviation(NSArray *array);
a source to share