Search code examples
cmacros

C Macro with a function errors out: expression cannot be used as a function


Inspired from this, I am trying to write my Macro that uses a function inside, and fail:

#include <string.h>

// Define a helper macro to get the file name from __FILE__
#define FILENAME_ONLY(file) (strrchr(file, '/') ? strrchr(file, '/') + 1 : file)

// Use the helper macro to create MYFILENAME
#define MYFILENAME FILENAME_ONLY(__FILE__)

// Create __MYFILE__ macro
#define __MYFILE__ "[" MYFILENAME "]"

#include <stdio.h>

int main() {
    printf("%s\n", __MYFILE__);
    return 0;
}

I get:

main.cpp:4:80: error: expression cannot be used as a function
 #define FILENAME_ONLY(file) (strrchr(file, '/') ? strrchr(file, '/') + 1 : file)

What am I missing please?


Solution

  • You can only concatenate the string literals this way.

    Example:

    printf("%s", "{" "hello" " " "world" "\n");
    

    The concatenation can only happen at the compile time.

    You can't use anything but the string literals this way.

    Your macro expands to:

        printf("%s\n", "[" (strrchr("/app/example.c", '/') ? strrchr("/app/example.c", '/') + 1 : "/app/example.c") "]");
    

    and it does not meet this criteria.

    As a general remark - avoid macros and use only if you really understand what you are doing. Macros can be very dangerous.

    Simple example:

    #define INC(x) ((x)++)
    
    int foo(int y)
    {
        return INC(y++);
    }