tags:

views:

48

answers:

1

With gnu89:

/* share.h */
extern inline void f (void);
/* function.c */
void f (void) {}
/* main.c */
#include "share.h"
int main (int argc, char **argv) {
    f ();
    return 0;
}

With C99:

/* share.h */
static inline void f (void) {}
/* main.c */
#include "share.h"
int main (int argc, char **argv) {
    f ();
    return 0;
}

How to implement one definition of f() in function.c like in gnu89 but using C99 mode ?

A: 

You put the inline definition the header file without extern and add an extern declaration/prototype in a source file:

/* share.h */
inline void f(void) {}

/* function.c */
#include "share.h"
extern void f(void);

/* main.c */
#include "share.h"
int main(int argc, char *argv[])
{
    f();
    return 0;
}

See http://www.greenend.org.uk/rjk/2003/03/inline.html for more information about inline in C.

If you really want to keep all your definitions (inline or not) in function.c like you say:

/* share.h */
#define WANT_INLINE 1
#include "function.c"

/* function.c */
#ifdef WANT_INLINE
inline void f(void) {}
#else
#include "share.h"
extern void f(void);
#endif

Not heavily tested and not recommended.

schot
Sorry if I wasn't clear, I want the function definition to be in the source file to keep the logic in only one file, whether functions are to be inlined or not.
lxndr
I do not think this is possible. To make inlining possible, a translation unit needs to know the function definition, so it must be in the header file.Maybe you could do this using some weird conditional inclusion, I'll try to add that to my answer.
schot
Well, it might be more readable to write the definition directly in the header file then. Does this mean that extern inline makes no sense in C99 ?
lxndr
You can make the function *declaration* extern inline instead of inline (same effect). You are right that extern inline *definition* makes no sense in C99: Then every inclusion generates stand-alone code, which means duplicate symbols when you include it more then once. And if you want to include it only once you could have just made it static inline. Hope this was useful to you.
schot
Very useful, thank you schot.
lxndr