Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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++);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading