Search code examples
cgccstaticinline-functions

Declare function as non-static and implement as static inline


I want to write different implementations for my function, some inline and some not. Thus, I want to declare the function as:

// MyHeader.h
int myFunc(void);

#if DO_INLINE
static inline int myFunc(void) { return 42; }
#endif

And then also have:

// MySource.c
#if !DO_INLINE
#include "myHeader.h"
int myFunc(void) { return 42; }
#endif

I'll specify DO_INLINE at compile time.

MSVC has no problems with this, but GCC (4.1.1) complains that I'm declaring a static function after I've already declared it as non-static. If I remove the static qualifier, and #include "MyHeader.h" from more than one compilation unit, it will complain about multiple definitions. (As if the inline functions are extern.) I don't quite understand why the compiler has problems with this.

I think this should be pretty obvious and unambiguous:

int myFunc(void);
static inline int myFunc(void) { return 42; }

It shouldn't require the declaration to be static.

That said, there is a solution to my problem that I'm trying very hard to avoid:

#if DO_INLINE
#define MAYBE_STATIC static
#else
#define MAYBE_STATIC 
#endif

MAYBE_STATIC int myFunc(void);

EDIT: Here is a more realistic use case for this: http://codepad.org/OkC0Su3v


Solution

  • Figured it out closely enough. The implementation should be defined as "extern inline" instead:

    // MyHeader.h
    int myFunc(void);
    
    #if DO_INLINE
    extern inline int myFunc(void) { return 42; }
    #endif
    

    The compiler will inline this function where it sees fit, but still compile it once as a function, to make it available for linking. That part I don't need, but it doesn't really hurt.