为什么指针增量语句被优化掉了?
Why is a pointer increment statement optimized away?
我已经编写了一种方法来解析来自 GPS 的字符串,但出于某种原因,在不使用 -O0
时优化了关键行。方法代码如下:
bool Gps::ParsePMTK_ACK(PmtkAck_t &dst, uint8_t *buf, int32_t size)
{
// Verify message ID
uint8_t *pCur = buf;
memset(&dst, 0, sizeof(dst));
if (strncmp((char*)pCur, "$PMTK001", 8) != 0) {
return false;
}
pCur = pCur + 8; // <--- This line gets optimized away when not on -O0
// thus causing the pointer to NOT be incremented
if (*pCur != SEPARATOR) {
return false;
}
++pCur; // <--- Not optimized away
if (ProcessInt(dst.cmd, &pCur) != 1) {
return false;
}
int16_t tmp;
if (ProcessInt(tmp, &pCur) != 1) {
return false;
}
dst.flag = static_cast<AckFlag_t>(tmp);
return true;
} // end ParsePMTK_ACK
删除此行后,函数无法处理格式正确的消息,因为 pCur==buf
在 if (*pCur != SEPARATOR)
条件。因此,函数 returns false
在格式正确的消息上,因为当到达 if 语句时指针指向错误的字符。
为什么指定的行被优化器完全删除了?有没有更好的实现方式,即使启用了优化器,我也能实现所需的行为(即,指针递增)?
我想编译器会转换您的原始代码:
pCur = pCur + 8; // <--- This line gets optimized away when not on -O0
// thus causing the pointer to NOT be incremented
if (*pCur != SEPARATOR) {
return false;
}
++pCur; // <--- Not optimized away
变成这样的东西:
if (*(pCur + 8) != SEPARATOR) {
return false;
}
pCur += 9;
因此在调试时造成混乱。
我已经编写了一种方法来解析来自 GPS 的字符串,但出于某种原因,在不使用 -O0
时优化了关键行。方法代码如下:
bool Gps::ParsePMTK_ACK(PmtkAck_t &dst, uint8_t *buf, int32_t size)
{
// Verify message ID
uint8_t *pCur = buf;
memset(&dst, 0, sizeof(dst));
if (strncmp((char*)pCur, "$PMTK001", 8) != 0) {
return false;
}
pCur = pCur + 8; // <--- This line gets optimized away when not on -O0
// thus causing the pointer to NOT be incremented
if (*pCur != SEPARATOR) {
return false;
}
++pCur; // <--- Not optimized away
if (ProcessInt(dst.cmd, &pCur) != 1) {
return false;
}
int16_t tmp;
if (ProcessInt(tmp, &pCur) != 1) {
return false;
}
dst.flag = static_cast<AckFlag_t>(tmp);
return true;
} // end ParsePMTK_ACK
删除此行后,函数无法处理格式正确的消息,因为 pCur==buf
在 if (*pCur != SEPARATOR)
条件。因此,函数 returns false
在格式正确的消息上,因为当到达 if 语句时指针指向错误的字符。
为什么指定的行被优化器完全删除了?有没有更好的实现方式,即使启用了优化器,我也能实现所需的行为(即,指针递增)?
我想编译器会转换您的原始代码:
pCur = pCur + 8; // <--- This line gets optimized away when not on -O0
// thus causing the pointer to NOT be incremented
if (*pCur != SEPARATOR) {
return false;
}
++pCur; // <--- Not optimized away
变成这样的东西:
if (*(pCur + 8) != SEPARATOR) {
return false;
}
pCur += 9;
因此在调试时造成混乱。