我基本上确信我遇到了一些 g++ 4.8.3 的错误,但我想我会先问这个列表,因为我对 setjmp/longjmp 的经验很少。我已将有问题的代码简化为以下 foo.cxx:
#include <setjmp.h>
#include <string.h>
// Changing MyStruct to be just a single int makes the compiler happy.
struct MyStruct
{
int a;
int b;
};
// Setting MyType to int makes the compiler happy.
#ifdef USE_STRUCT
typedef MyStruct MyType;
#elif USE_INT
typedef int MyType;
#endif
void SomeFunc(MyType val)
{
}
static void static_func(MyType val)
{
SomeFunc(val);
}
int main(int argc, char **argv)
{
jmp_buf env;
if (setjmp(env))
{
return 1;
}
MyType val;
#ifdef USE_STRUCT
val.a = val.b = 0;
#elif USE_INT
val = 0;
#endif
// Enabling the below memset call makes the compiler happy.
//memset(&val, 0, sizeof(val));
// Iterating 1 or 2 times makes the compiler happy.
for (unsigned i = 0; i < 3; i++)
{
// calling SomeFunc() directly makes the compiler happy.
static_func(val);
}
return 0;
}
我使用 g++ 4.8.3 来编译这段代码。令我感兴趣的是,当我定义 USE_STRUCT 时,编译失败但使用 USE_INT 成功。代码中有注释进一步说明了如何使用 USE_STRUCT 使编译成功。g++ 的 -fPIC 选项也只会导致编译失败,但这是我的环境中的必需参数。
查看编译错误:
g++ -DUSE_STRUCT -Wextra -Wno-unused-parameter -O3 -Werror -fPIC foo.cxx
foo.cxx: In function ‘int main(int, char**)’:
foo.cxx:26:5: error: variable ‘val’ might be clobbered by ‘longjmp’ or ‘vfork’ [-Werror=clobbered]
但是使用简单的 int 就可以了:
g++ -DUSE_INT -Wextra -Wno-unused-parameter -O3 -Werror -fPIC foo.cxx
有人可以向我解释为什么 val 如果它是一个结构而可能会被破坏,但如果它是一个 int 则不会?如代码中的注释所示,有关使结构成功编译的其他方法的任何见解?或者这是否指向编译器错误?
非常感谢任何见解和评论。