简体   繁体   English

尝试在#define 宏中使用 __attribute__ 来支持 MSVC 和 G++,但存在编译问题

[英]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.在我的项目中,我有一个 function ,其行为类似于sprintf ,如果格式字符串中存在参数不匹配,我想启用编译器警告。 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++.我知道这在 MSVC 中是不可能的,但是因为我的项目是用 MSVC 和 G++ 编译的,所以我想实现一个独立于平台的宏,将必要的 __attribute__ 添加到 Z3CD270942B7B02F3400 上的 function 中。 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.如果编译器是 MSVC (Win32),那么这应该评估为空。 If it's G++, it should be replaced with the __attribute__ specifier.如果是 G++,则应将其替换为__attribute__说明符。 However when I try to compile the following function, it fails with both compilers:但是,当我尝试编译以下 function 时,两个编译器都失败了:

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')在 linux (G++) 上,编译器会说以下内容:(是的,“预期”之后的那些确切字符)

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:如果我在 MSVC 上编译,它会给我这个错误:

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++?我是否误解了#define宏在 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.我的ATTR_PRINTF_CHECK宏是在不同的 header 文件中定义的,该文件显然不包含在当前的 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.我没有早点弄清楚这一点的原因是因为我的 IDE (CLion) 没有警告我该宏不存在,甚至将其突出显示为有效的宏,以及智能感知和 ctrl 单击导航。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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