Search code examples
c++macrostraceexpansion

Macro expansion and concatenation in cpp


#include <string>

using namespace std;

#define PRINT_INFO() printf("%s",__FUNCTION__)
#define PRINT(str,...) printf("%s %s", PRINT_INFO(), str, ##__VA_ARGS__)

int main() {
    PRINT_INFO(); // expected output = main
    PRINT("Hello %s", "World"); // expected output = main Hello World
    return 0;
}

Consider the above code snippet in c++. My intention is to use the PRINT_INFO() macro inside PRINT() macro in a way that will also print the parameters sent from main.

However, I am getting >> Command terminated by signal 11

How can I get what I intend to get?


Solution

  • Think about what happens as the PRINT macro is expanded:

    printf("%s %s", PRINT_INFO(), str, ##__VA_ARGS__)
    -> printf("%s %s", printf("%s",__FUNCTION__), str, ##__VA_ARGS__)
    

    I don't think this is what you intended.

    Perhaps you meant:

    #define PRINT_INFO() printf("%s ",__FUNCTION__)
    #define PRINT(str,...) do { PRINT_INFO(); printf(str, ##__VA_ARGS__); } while(0)
    

    I don't see the value that having two macros adds. Another option would be:

    #define PRINT(str,...) printf("%s:%d: "  str, __FUNCTION__, __LINE__, ##__VA_ARGS__)
    

    This gives the line information as well, you can just remove that if you do not want it.