[英]error “cannot appear in a constant-expression” in g++ but not in gcc
98 static inline int set_hw_br(pid_t tracee, dr7_t *pdr7, void *addr, int dr_index)
99 {
100 errno = 0;
101 printf("LINE = %d <pid> %d, dr_index= %d addr=%u \n",__LINE__, tracee, dr_index, addr);
102 //if (ptrace(PTRACE_POKEUSER, tracee, offsetof(struct user, u_debugreg[dr_index]), addr))
103 if (ptrace(PTRACE_POKEUSER, tracee, offsetof(struct user, u_debugreg[dr_index]), addr))
104 {
105 int ii = errno;
106 printf("MKH: 22 errno = %d\n", ii);
107 ptrace(PTRACE_DETACH, tracee, 0, 0);
108 return -1;
109 }
110 else
111 printf("PTRACE_POKEUSER passed...\n");
以上代码(部分主要代码)已在GCC编译器中成功编译。 但是,当通过G ++进行编译时,它却出现了错误: error: 'dr_index' cannot appear in a constant-expression
在第103行error: 'dr_index' cannot appear in a constant-expression
中。set_hw_br是从另一个函数调用的。
知道为什么这在g ++中会失败吗?
谢谢。
offsetof
宏要求成员标识符必须产生一个地址常数(C11 7.19 / 3):
offsetof(type, member-designator)
它扩展为一个整数常量表达式,其类型为
size_t
,其值是从结构的开头(由type 指定 )到结构成员(由member-designator指定 )的偏移量(以字节为单位)。 类型和成员代号应使static type t;
然后表达式
&(t.
-designator)
得出一个地址常数。 (如果指定的成员是位字段,则行为未定义。)
在您的代码中, t.u_subreg[dr_index]
不是常数,因为dr_index
不是常数。
GCC使用编译器内部函数实现offsetof
,因此offsetof
表达式中允许的内容取决于GCC内部函数的规则。 作为标准的扩展,GCC C前端允许使用非恒定表达式作为输入并产生非恒定结果。 C ++前端不允许这样做,并给出错误消息,告诉您dr_index
无法在此处使用。
您可以将offsetof
表达式更改为仅使用常量:
offsetof(struct user, u_debugreg[0])
然后可以向其添加索引,其中T
是数组u_debugreg
的类型:
offsetof(struct user, u_debugreg[0]) + sizeof(T)*dr_index
(这假设u_debugreg
是实际数组,而不是指针)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.