在c ++ 11模式下奇怪的g ++预处理器行为

Rud*_*udi 6 c++ g++ c++11

我有一个问题,当g ++在c ++ 11模式下运行时,某些预处理器宏未正确扩展.这使我在使用Qt编译程序时遇到麻烦.

$ g++ --version
g++ (GCC) 4.7.2
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Run Code Online (Sandbox Code Playgroud)

以下剪辑揭示了问题:

$ cat foo.cpp
//#include <QtGui>
#define QTOSTRING_HELPER(s) #s
#define QTOSTRING(s) QTOSTRING_HELPER(s)
#ifndef QT_NO_DEBUG
# define QLOCATION "\0"__FILE__":"QTOSTRING(__LINE__)
# define METHOD(a)   qFlagLocation("0"#a QLOCATION)
# define SLOT(a)     qFlagLocation("1"#a QLOCATION)
# define SIGNAL(a)   qFlagLocation("2"#a QLOCATION)
#else
# define METHOD(a)   "0"#a
# define SLOT(a)     "1"#a
# define SIGNAL(a)   "2"#a
#endif

METHOD(grml)
Run Code Online (Sandbox Code Playgroud)

在没有c ++ 11的情况下对其进行预处理是正确的.

$ g++ -E foo.cpp
# 1 "foo.cpp"
# 1 "<command-line>"
# 1 "foo.cpp"
# 15 "foo.cpp"
qFlagLocation("0""grml" "\0""foo.cpp"":""15")
Run Code Online (Sandbox Code Playgroud)

但是在C++ 11模式下,QTOSTRING宏不会扩展,导致源代码行出现编译错误.

$ g++ -std=c++11 -E foo.cpp
# 1 "foo.cpp"
# 1 "<command-line>"
# 1 "foo.cpp"
# 15 "foo.cpp"
qFlagLocation("0""grml" "\0"__FILE__":"QTOSTRING(15))
Run Code Online (Sandbox Code Playgroud)

这种行为是否有意,我该怎么做才能启用扩展?

小智 9

这是一个已知问题,新的GCC行为是有意的,因为新的C++ 11特性,即用户定义的文字.您可以在之前插入空格__FILE__QTOSTRING确保始终将其视为单独的标记,从而进行扩展.

QT bug报告在这里.