Objective C: Inline function - symbol not found

2020-03-01 08:23发布

问题:

I have a library which uses an inline C function, and is compiling just fine. When another library references that library, it still compiles fine. But if an actual app references the library, it fails to compile, saying that the _functionNameHere (yes, function name beginning with underline) - symbol is not found.

If I remove the inline specifier, it all compiles fine. But as long as a function is inline inside the library, the app can't compile!

Any ideas as to why that is?

I know pretty much about compilers, but am new to the Objective-C, and anything I know about it is nothing more than educated guesses. And even that way I can't think of a reason that it will behave that way.

The thing is, the inline function is INLINE, which means there's no symbol at all, it is compiled inline wherever it is called, and the referencing app should not even know it ever existed. That's true as long as the inline function is always inline-able, and is private to the library, and there's no special compiler configuration which prevents inlining, and all of those are true.

So, anyone please come and point the finger at what I'm doing/thinking wrong...

Thanks :-)

回答1:

You should add the static specifier to your inline function definition if the function is intended for use only in the same translation unit (internal linkage),

static inline int add(int x, int y) {return x+y;}
int s = add(1, 2);

If you omit static in the example above (in Debug configuration, where no optimization is performed and no inlining is carried out), the linker will exit with error complaining _add is referenced but Symbol(s) not found.

In C99, an inline function declaration without any storage specifier will not generate an actual callable function body so the linker gives an error when it needs one.

If your inline function may be used by other modules, it's more complicated. A common practice is to include the inline function definition (without extern) in the header file and include exactly one prototype declaration with extern in exactly one module.

A good article explaining inline functions in C99: http://www.drdobbs.com/184401540



回答2:

just add FOUNDATION_EXPORT to function on the header (.h). Remember import Foundation/Foundation.h (OS X) or UIKit/UIKit.h (ios).

Example:

//.h
#import <UIKit/UIKit.h>

FOUNDATION_EXPORT inline NSString * myInlineFunction(void);