0

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

1
  • 1
    Succinctly, the answer is no. Not like that. Commented Nov 18, 2021 at 13:36

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Source text inside #if preprocessor groups can be indented for clarity.
1

You can inverse #define and #ifdef:

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

1 Comment

Source text inside #if preprocessor groups can be indented for clarity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.