Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect that extern "C" is in effect

I am trying to find all places where #include is placed inside extern C block. Is is possible to check this using preprocessor? I would like to do add something like this to my header files:

#ifdef EXTERN_C_IS_IN_EFFECT
#error File included from extern "C" block!
#endif

I am also looking for other ways to fail compilation in such case, e.g. use some special attribute. I am using gcc 4.4.7.

I defined following macro and then use it in every header which needs protection against inclusion in extern C block:

#define ASSERT_NO_EXTERN_C void assert_no_extern_c(int); void assert_no_extern_c(double);
like image 553
Daniel Frużyński Avatar asked Apr 17 '15 09:04

Daniel Frużyński


2 Answers

Maybe you can define 2 function prototypes with same name and different parameters. You will get warnings in case of extern "C" block. And it is allowed in C++.

like image 90
i486 Avatar answered Nov 14 '22 23:11

i486


That's not possible because the preprocessor runs before any syntactical analysis is done; that is, the preprocessor doesn't even know what extern "C" is and it's action cannot depend on the presence of such a directive either.

However, linkage specifications do nest, so instead of making sure the includer did not specify extern "C", you could place your header within an extern "C++" specification to make sure that it uses C++ linkage.

like image 31
fuz Avatar answered Nov 15 '22 00:11

fuz