I am trying to put a C-style function in the header of an Objective-C class. (My terminology might be wrong here -- I'm just used to writing Objective-C class methods rather than functions). It looks as follows:
// Sort function
NSInteger sort(NSString *aString, NSString *bString, void *context);
NSInteger sort(NSString *aString, NSString *bString, void *context) {
return [aString compare:bString options:NSNumericSearch];
}
Unforuntately this results in:
Expected '=', ',', ';', 'asm' or 'attribute' before '{' token
Any ideas as to what I'm missing? Thank you.
header files are simply files in which you can declare your own functions that you can use in your main program or these can be used while writing large C programs. NOTE:Header files generally contain definitions of data types, function prototypes and C preprocessor commands.
Because a header file might potentially be included by multiple files, it cannot contain definitions that might produce multiple definitions of the same name. The following are not allowed, or are considered very bad practice: built-in type definitions at namespace or global scope. non-inline function definitions.
An Objective-C function is declared using the following syntax: <return type> <function name> (<arg1 type> <arg1 name>, <arg2 type> <arg2 name>, ... ) Explanations of the various fields of the function declaration are as follows: <return type> - Specifies the data type of the result returned by the function.
My guess is that you put the function definition within the @interface of your class. Instead, make sure C style function declarations are outside of Objective-C @interface declarations:
// declare C functions here
NSInteger sort(NSString *aString, NSString *bString, void *context);
@interface MyClass : NSObject
{
// class instance vars
}
// class properties & instance methods
@end
The body of your function needs to be in the .m file instead of in the header.
As long as the declaration of your function (NSInteger sort(NSString *aString, NSString *bString, void *context);
) remains in the header you'll still be able to access the sort function from anywhere you import the header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With