views:

39

answers:

1

My library contains a function that is used both internal and external. The function is so small that I want the compiler to try to inline function when called internal. Because the function uses information of an incomplete type external calls cannot be inlined. So my module should also always contain a copy of the function with external linkage.

I think I found the following solution, but would like your advice:

/* stack.h */
struct stack;
extern bool stack_isempty(struct stack *s);

/* stack.c */
#include "stack.h"
struct stack { [...]; int size; };
inline bool stack_isempty(struct stack *s) { return s->size == 0; }

Usually I use inline the other way around or only put a static inline function in the header file. But as explained this is not possible here.

Does this approach give the desired results? Does anyone see any disadvantages to this approach (Is it portable C99)?

+4  A: 

That looks perfectly fine under the C99 rules. Because stack.c is compiled with both an extern and inline declaration of the function, it will be defined with external linkage and can also be inlined within that file.

Other files will have only the declaration, and so will link to the version with external linkage.

Note that the function isn't allowed to define any modifiable objects with static storage duration, or reference any functions or global variables that aren't extern.

caf
Thanks. Meanwhile I thought of 3 possible issues, but they are all nonsense: 1. The order of definition and declaration for inline functions; 2. The linkage of structure declarations; 3. Users supplying their own inline definition that 'override' mine.
schot