3

If a function shall be used form C and C++ code the declaration of this function (usually in a header file) has to be surrounded by

#ifdef __cplusplus
    extern "C" {
#endif

// function declarations

#ifdef __cplusplus
   }
#endif

We are merging for C to C++ and now we have to introduce this into a lot of header files.

Almost all headers now have these line at the very top and bottom, respectively.

This reminds me of header guards.

 #ifndef SOMESYMBOL
 #define SOMESYMBOL

 // content of the header file

 #endif

Is there a way (like #pragma once) to declare the extern C linkage only at the top? This linkage behaviour should hold for the entire file. I like to avoid the closing bracket at the end.

schorsch312
  • 5,553
  • 5
  • 28
  • 57
  • No there's no such preprocessor `#pragma` AFAIK. – πάντα ῥεῖ Aug 19 '19 at 09:41
  • 3
    Possible duplicate of [Could we use extern "C" in C file without #ifdef \_\_cplusplus?](https://stackoverflow.com/questions/9499078/could-we-use-extern-c-in-c-file-without-ifdef-cplusplus). Basically the only other thing I've seen being done is to have conditional defines like `EXTERN_C_BEGIN`/`EXTERN_C_END` which will be expanded as needed, which keeps you from writing `#ifdef __cplusplus` each time. – vgru Aug 19 '19 at 09:47
  • Keep in mind that #pragma once isn't even officially supported by the standard. It's something most compilers allow and use, but the compiler is also allowed to ignore it. – Bas in het Veld Aug 19 '19 at 09:48
  • Simply rename all the C header files to have a different extension (e.g. rename `file.h` to `file.inc`. Then recreate the headers (like `file.h`) that includes the originals, with appropriate checks as needed. All of the headers could follow a simple template, so writing a program (if needed) to generate them all would be simple. – Peter Aug 19 '19 at 10:13

0 Answers0