schmittsfn
schmittsfn

Reputation: 1442

How to write 'global' inline functions in Objective-C (using C syntax)

Assuming I'm including a header file in my precompiled header that includes a bunch of inline functions to be used as helpers wherever needed in any of the project's TUs -- what would be the correct way to write those inlines?

1) as static inlines? e.g.:

static inline BOOL doSomethingWith(Foo *bar)
{
   // ...
}

2) as extern inlines? e.g.:

in Shared.h

extern inline BOOL doSomethingWith(Foo *bar);

in Shared.m

inline BOOL doSomethingWith(Foo *bar)
{
   // ...
}

My intention with inlines is to:

So far I have only seen variant 1) in the wild. I have read (sadly can't find it anymore) that variant 1) does not accurately move the inline function's body into the callers but rather creates a new function, and that only extern inline ensures that kind of behavior.

Upvotes: 5

Views: 8560

Answers (2)

CRD
CRD

Reputation: 53010

Skipping whether you should be inlining at all for the reasons you give, the standard way to inline in Cocoa is to use the predefined macro NS_INLINE - use it either in the source file using the function or in an imported header. So your example becomes:

NS_INLINE BOOL doSomethingWith(Foo *bar)

For GCC/Clang the macro uses static and the always_inline attribute.

Most (maybe all) compilers won't inline extern inline as they operate on a single compile unit at a time - a source file along with all its includes.

Upvotes: 7

user529758
user529758

Reputation:

make the code less verbose by encapsulating common instructions

Non-inline functions do that as well...

to centralize the code they contain to aid with future maintenance

then you should have non-inline functions, don't you think?

to use them instead of macros for the sake of type safety

to be able to have return values

those seem OK to me.


Well, when I write inline functions, I usually make them static - that's typically how it's done. (Else you can get all sorts of mysterious linker errors if you're not careful enough.) It's important to note that inline does not affect the visibility of a function, so if you want to use it in multiple files, you need the static modifier.

An extern inline function does not make a lot of sense. If you have only one implementation of the function, that defeats the purpose of inline. If you use link-time optimization (where cross-file inlining is done by the linker), then the inline hint for the compiler is not very useful anyway.

only extern inline insures that kind of behavior.

It doesn't "ensure" anything at all. There's no portable way to force inlining - in fact, most modern compilers ignore the keyword completely and use heuristics instead to decide when to inline. In GNU C, you can force inlining using the __attribute__((always_inline)) attribute, but unless you have a very good reason for that, you shouldn't be doing it.

Upvotes: 5

Related Questions