简体   繁体   中英

Trying to use __attribute__ in a #define macro to support MSVC and G++, having compile issues

In my project I have a function that behaves similarly to sprintf , and I would like to enable compiler warnings if there is a parameter mismatch in the format string. I know that this is not possible in MSVC, but because my project is compiled with both MSVC and G++, I wanted to implement a platform-independent macro that adds the necessary __attribute__ to the function on G++. To achieve this, I wrote this macro:

#if WIN32
    #define ATTR_PRINTF_CHECK(formatIndex, firstParamIndex)
#else
    #define ATTR_PRINTF_CHECK(formatIndex, firstParamIndex) \
        __attribute__ ((format (printf, formatIndex, firstParamIndex)))
#endif

If the compiler is MSVC (Win32), then this should evaluate to nothing. If it's G++, it should be replaced with the __attribute__ specifier. However when I try to compile the following function, it fails with both compilers:

void Log(CLogSeverity _severity, const char *format, ...) ATTR_PRINTF_CHECK(3, 4);

On linux (G++) the compiler says the following: (Yes, those exact characters after 'expected')

logger.h:39:61: error: expected ‘;’ at end of member declaration
void Log(CLogSeverity _severity, const char *format, ...) ATTR_PRINTF_CHECK(3, 4);

If I compile on MSVC, it gives me this error:

error C3646: 'ATTR_PRINTF_CHECK': unknown override specifier
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2059: syntax error: '('
// and a bunch of other garbage

Am I misunderstanding the way #define macros work in C/C++? Am I not allowed to use them to insert compiler-specific attributes?

I found the cause of this problem. My ATTR_PRINTF_CHECK macro was defined in a different header file, which apparently wasn't included in the current header. So both compilers were trying to interpret the macro as a special attribute.

The reason why I didn't figure this out sooner is because my IDE (CLion) didn't warn me that the macro doesn't exist, and even highlighted it as a valid macro, along with intellisense and ctrl-click navigation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM