views:

119

answers:

2

I was reading up about bypassing objective-c's messaging to gain performance (irrelevant to this specific question) when i found an interesting bit of code:

#import <Cocoa/Cocoa.h>

@interface Fib : NSObject { }

- (long long) cFib: (NSUInteger) number;

@end

@implementation Fib

// c implementation of fib
long long cFibIMP(NSUInteger number)
{
  return (number < 3) ? 1 : cFib(number - 1) + cFib(number - 2);
}

// method wrapper for c implementation of fib
- (long long) cFib: (NSUInteger) number
{
  return cFibIMP(number);
}

@end

My question is; when using c function, within an objective-c object, what scope is the c function (cFibIMP in this particular case) placed in? Does the objective-c class encapsulate the c function removing change of name-clash or is the c function simply dumped into the global scope of the whole objective-c program?

+4  A: 

The functions are dumped in the "global" scope.

You can check this by adding a new class at the end of your sample code:

@interface Gib : NSObject {}
@end
@implementation Gib
- (void) t
{
    NSLog(@"%d", cFibIMP(10));
}
@end
diciu
+1  A: 

The C function has global scope.

If you want to have something like "class" scope, your best bet is probably to use the static keyword, which limits the scope of the function to the source file in which it is contained. For the sort of usage you're illustrating here, that's usually close enough.

Stephen Canon
so prepending static to the function declaration would restrict it's scope to the module then? Does this apply even though that static declaration is made internal to the @implementation as opposed to being made outside (i.e. at the beginning of the source code file?)
roja