Alexey Nezhdanov
Alexey Nezhdanov

Reputation: 127

C: Is there a way to define a macro AND output some code in a single statement?

I would like to define a macro that would generate program text for me AND also set some non-string macro value. I know that including #define in another #define is not going to work so I'm trying to find a different way.

A simple example:

#include <stdio.h>

#define START_SYNTHETIC int SYNTHETIC_FUNCTION() {
#define END_SYNTHETIC return 0;}


#define SYNTHETIC_FUNCTION my_function

START_SYNTHETIC
    printf("Hello from %s", "SYNTHETIC_FUNCTION");
END_SYNTHETIC


int main() {
    my_function();
}

This code kinda works, it produces the following output:

Hello from SYNTHETIC_FUNCTION

There are two problems with it:

  1. function name is not expanded and I just have "SYNTHETIC_FUNCTION" in the output. This is currently not critical but might be needed later on.

  2. I dislike having three lines to start my synthetic function. The empty line inserted by autoformatter is especially irritating. Can I reduce this to just a single macro invocation?

Upvotes: 0

Views: 116

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

Is there a way to define a macro AND output some code in a single statement?

No, in C macros can't define other macros.

function name is not expanded and I just have "SYNTHETIC_FUNCTION" in the output.

Sure it doesn't - it's inside a string literal. Macro replacement is not done inside a string literal.

Can I reduce this to just a single macro invocation?

I do not understand the point at all of this code. Just use __func__.

int my_function(void) {
    printf("Hello from %s\n", __func__);
    return 0;
}

or pass the name as a macro parameter:

#define SYNTHETIC(name) \
int name(void) { \
    printf("Hello from %s\n", #name); \
    printf("but really, just use __func__ anyway...: %s\n", __func__); \
    return 0; \
}

SYNTHETIC(my_function)

Upvotes: 1

Related Questions