Inline Functions in C
Inline Functions in C
Introduction
GNU C (and some other compilers) had inline functions long before standard
C introduced them (in the 1999
standard); this page summarizes the rules they
use, and makes some suggestions as to how to actually use
inline
functions.
There are various ways to define inline functions; any given kind of
definition might definitely emit stand-
alone object code, definitely not emit
stand-alone object code, or only emit stand-alone object code if it is
known to be needed. Sometimes this can lead to duplication of object code,
which is a potential problem for
following reasons:
1. It wastes space.
2. It can cause pointers to what is apparently the same function to compare
not equal to one another.
3. It might reduce the effectiveness of the instruction cache. (Although
inlining might do that in other
ways too.)
If any of these are a problem for you then you will want to use a strategy
that avoids duplication. These are
discussed below.
Such functions may not contain modifiable static variables, and may not
refer to static variables or
functions elsewhere in the source file where
they are declared.
return a > b ? a : b;
return a > b ? a : b;
return a > b ? a : b;
return a > b ? a : b;
(If you think I've misinterpreted these rules, please let me know!)
This is of rather limited use: if you only want to use the function from
one translation unit then static
inline below makes more sense, if not the
you probably want some form that allows the function to be
inlined in more
than one translation unit.
However it does have the advantage that by defining away the inline
keyword, the program reduces to
a portable program with the same meaning
(provided no other non-portable constructions are used).
This provides sensible semantics (you can avoid duplicate copies of the
functions' object code) but is a
bit inconvenient to use.
# define __GNUC_GNU_INLINE__ 1
#endif
return a > b ? a : b;
You can support legacy compilers (i.e. anything without inline) via
-Dinline="", although this may
waste
space if the compiler does not optimize out unused functions..
#ifndef INLINE
#endif
return a > b ? a : b;
#include "header.h"
return a > b ? a : b;
#include "header.h"
To support legacy compilers, you have to swap the whole thing around so
that the declarations are
visible in the common header and the definitions
are restricted to a single translation unit, with inline
defined away.
# else
# endif
#endif
return a > b ? a : b;
#include "header.h"
Supporting legacy compilers has the same issues as the GNU C model.
RJK | Contents