How to define a function for internal and external copy inside C99

My library contains a function that is used both internally and externally. The function is so small that I want the compiler to try to inline the function when calling internal. Since the function uses information of an incomplete type, external calls cannot be embedded. Therefore, my module should also always contain a copy of the function with external communication.

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 in another way or just put the static inline function in the header file. But, as explained, this is not possible here.

Does this approach get the desired results? Does anyone see flaws in this approach (does it carry the C99)?

+4
source share
1 answer

It looks great according to C99 rules. Since stack.c compiled with both an extern declaration and an inline function, it will be defined using external binding and can also be embedded in this file.

Other files will only have a declaration and therefore will refer to an external link version.

Note that functions are not allowed to define any mutable objects with static storage duration or to refer to any functions or global variables that are not extern .

+5
source

All Articles