Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-C function declaration in header

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.

like image 598
serverpunk Avatar asked Oct 24 '11 23:10

serverpunk


People also ask

Can you put functions in a header file in C?

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.

Can you define functions in header file?

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.

How do you write a function in Objective-C?

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.


2 Answers

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
like image 188
LearnCocos2D Avatar answered Sep 21 '22 15:09

LearnCocos2D


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.

like image 44
Lawrence Johnston Avatar answered Sep 22 '22 15:09

Lawrence Johnston