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?
The issue you're encountering is due to the fact that macros are expanded by the preprocessor before the actual compilation takes place. When you use a function inside a macro, the function is not yet defined at the time of macro expansion, leading to the error you're seeing.
To fix this, you should ensure that the necessary function prototypes are available before the macro is expanded. In this case, you're using the strrchr function, which is declared in the string.h header. You should include this header before defining the macro.
Here's the corrected code:
#include <string.h> #include <stdio.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 "]" int main() { printf("%s\n", __MYFILE__); return 0; }
By including string.h at the top, you ensure that the strrchr function prototype is available when the macro is expanded. This should resolve the error you're seeing.