0

Is it pointless to have:

#ifdef __cplusplus
  extern "C" {
#endif

// code...

#ifdef __cplusplus
  }
#endif

Where "code..." is just a bunch of defines and typedefs (no includes, etc.)?

August Karlstrom
  • 10,773
  • 7
  • 38
  • 60
flmng0
  • 387
  • 1
  • 2
  • 14

2 Answers2

2

In principle, in your particular case (no variable or function declaration), the extern "C" is pointless.

In practice, it makes the code more readable (showing the intent of defining a C++ friendly interface) and less brittle. Some developer (perhaps you) might (in a few months) add other declarations inside it.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Thank you for the reply. But I don't work as a team, I'm a grade 9 school student who does this as a hobby. Even though I would love to work in a team; no-one else in my school programs. – flmng0 Jun 10 '17 at 05:42
  • But even if you are alone, you need to write some code that you'll be able to understand in a few months – Basile Starynkevitch Jun 10 '17 at 07:06
  • Good point, I've decided to fully comment my code and add the extern "C" to every header file. I'm going to put a repo on github too. – flmng0 Jun 10 '17 at 07:07
1

It depends on how you intend the header to be used.

If the types and values are valid and have the same meaning in both C and C++, and you intend to use them from some compilation units compiled as C and others compiled as C++, then you need to use extern "C" when compiling as C++. Otherwise, your C++ code and C code cannot interoperate.

If the header file is included by compilation units will only ever be built as C, as C++, but never as both, then you don't need extern "C". And you can use features specific to your chosen language.

Peter
  • 35,646
  • 4
  • 32
  • 74
  • Thank you very much. I've decided to exclude the extern "C". This is simply just because the only typedef is unsigned char, and the defines are just hexa-decimal integer values. – flmng0 Jun 10 '17 at 05:40
  • 1
    Depending on your needs, you may wish to consider using `const`s, rather than `#define`s. The advantages of `const`, assuming a reasonable quality compiler, tend to exceed the benefits of using macros. For more information see https://stackoverflow.com/questions/6442328/what-is-the-difference-between-define-and-const and linked duplicates. – Peter Jun 10 '17 at 05:59