简体   繁体   中英

Define a preprocessor macro with preprocessor comands

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

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

You can inverse #define and #ifdef :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM