3

I'm aware of the declaration of C header files with #ifdef and the meaning of extern before variables and functions. But recently I've got a third party library for an embedded device with the following scheme:

/* "lib.h" */
#ifndef LIB_H_
#define LIB_H_

   #ifdef LIB_C

      void function1();
      /* ... */

   #else

      extern void function1();
      /* ... */

   #endif

#endif /* LIB_H_ */

And additionally I've got a corresponding C source file:

/* lib.c */
#define LIB_C
#include "lib.h"

void function1()
   {
   /* ... */
   }

/* ... */

So here I am and a bit confused. What is the reason to declare all functions twice in the header in this way?

Cid
  • 31
  • 2
  • Hmm.. this is interesting....IIRC, functions are external linkage, by default. – Sourav Ghosh Nov 09 '16 at 13:42
  • 2
    Possible duplicate of [Extern functions in C vs C++](http://stackoverflow.com/questions/11712707/extern-functions-in-c-vs-c) – Baldrick Nov 09 '16 at 13:43
  • 1
    In general, code like that is dangerous. It means that somewhere in the two sections there is probably a significant difference (not merely the presence or absence of `extern`) between some functions for 'inside the library' and 'outside the library'. That's a problem because having the 'inside' code use the same definitions as the 'outside' code uses ensures that the two are synchronized — so if there's a difference, there could be a problem that the compiler won't diagnose. Note that the declaration isn't a prototype; it's merely a function with unspecified argument list (but no ellipsis). – Jonathan Leffler Nov 09 '16 at 14:33
  • I'd say the most likely explanation is that the person who wrote the code didn't know C in detail. Putting an `extern` before your function declarations can even startle intermediately experienced C programmers. It's good for posing. Kind of the same thing as declaring your local variables as `auto`. – Lundin Nov 09 '16 at 15:20

1 Answers1

4

It's either an affectation, or a compatibility hack for some non-conforming or ancient compiler. You don't need the extern version, but using it is also fine, because function declarations are extern by default.

In other words, it's cruft, but maybe someone needs that cruft. We can't know for sure.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436