Home > Software design >  Define a preprocessor macro with preprocessor comands
Define a preprocessor macro with preprocessor comands

Time:11-19

I'm using often a syntax like

#ifdef __cplusplus 
extern "C"
#endif
void myCFunc();

so I tried to make a macro to have a syntax like

CFUNC(void myCFunc());

I'm not relly sure if it's something that can be done (can preprocessor execute its freshly generate code?)

The failed idea was something like

#define CFUNC(ARGUMENT) \
#ifdef __cplusplus \
extern "C" \
#endif \
ARGUMENT;

Is there a way make a macro that generates code for the preprocessor?

Thanks

CodePudding user response:

You can define two different macros depending on the context:

#ifdef __cplusplus
#define CFUNC(ARGUMENT) extern "C" ARGUMENT;
#else
#define CFUNC(ARGUMENT) ARGUMENT;
#endif

CFUNC(FOO)

However, the common way to do this is the following. It includes the braces and can be used both in definitions and declarations.

#ifdef __cplusplus
#define EXTERN_C extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C
#define EXTERN_C_END
#endif

EXTERN_C
void foo(void) { ... }
EXTERN_C_END

CodePudding user response:

You can inverse #define and #ifdef:

#ifdef __cplusplus
#define CFUNC(ARGUMENT) \
extern "C" \
ARGUMENT;
#else
#define CFUNC(ARGUMENT) ARGUMENT;
#endif
  • Related