如何解决我得到“由于优化,此处无法访问变量x”
| 即使构建配置设置为“ Debug”且优化为False,我也会由于优化而在这里无法访问“变量ForAllUsers”。因此,我无法调试程序。 为什么我得到这个? 当我按下“运行”按钮时运行了哪个版本? 我怎么看procedure Test(ForAllUsers: boolean);
VAR
FName,Path1,Path2: string;
RootKey: HKEY;
begin
Result:= FALSE;
TRY
if ForAllUsers
then
begin
RootKey:= HKEY_CLASSES_ROOT;
Path1:= \'\';
Path2:= \'\';
end
else
begin
RootKey:= HKEY_CURRENT_USER; <----- Break point here
Path1:= \'\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\\';
Path2:= \'\\Software\\Classes\\\';
end;
...
结束;
更新:
自从我发布此问题仅几分钟时间,它就已经投票过两次,并两次出演。似乎这是一个很常见的问题。接受了大卫提供的答案。
解决方法
我们每个人都不时遭受这种痛苦。我有时要做的是在需要调试引用该变量但不执行任何操作的变量时添加一些虚假代码。例如:
if x>0 then x := x*1;
或者,如果它是布尔值,则:
if b then b := not not b;
这些做法通常足以使编译器写出使变量保持活动状态的代码,以便调试器可以对其进行检查。确保将代码放在例程的底部!并确保在签入代码之前记得将其删除。
, 让我们来看看有无优化的代码的区别:
procedure test;
var
x,y,z: integer;
begin
x:= 1; //x is stored in register EAX.
Inc(x);
y:= x; //this is a no-op because it\'s just a rename.
//After this point x is no longer used.
//Here you will get `Variable x inaccessible here due to optimization`
z:= 0; //z is never used
if (y = 1) then Inc(z); //because Delphi knows this code will never execute
end;
这是经过优化的汇编代码:
Project5.dpr.12: x:= 1; //x is stored in register EAX.
004085E8 B801000000 mov eax,$00000001
Project5.dpr.13: Inc(x);
004085ED 40 inc eax
Project5.dpr.18: if (y = 1) then Inc(z);
004085EE 48 dec eax //test to see if eax=1,triggers `jz` if true.
//Delphi put it in to facilitate the `if`,but
//is not smart enough to eliminate it :-)
Project5.dpr.19: end;
004085EF C3 ret
这是未经优化的代码:
Project5.dpr.11: begin //note that Delphi doesn\'t use registers,but the stack
//to keep variables.
004085E8 55 push ebp
004085E9 8BEC mov ebp,esp //init the stack frame.
004085EB 83C4F4 add esp,-$0c
Project5.dpr.12: x:= 1; //x is stored near the top of the stack.
004085EE C745FC01000000 mov [ebp-$04],$00000001
Project5.dpr.13: Inc(x);
004085F5 FF45FC inc dword ptr [ebp-$04]
Project5.dpr.14: y:= x; //y sits on the stack frame.
004085F8 8B45FC mov eax,[ebp-$04]
004085FB 8945F8 mov [ebp-$08],eax
Project5.dpr.17: z:= 0; //z is also in the stack frame.
004085FE 33C0 xor eax,eax
00408600 8945F4 mov [ebp-$0c],eax
Project5.dpr.18: if (y = 1) then Inc(z);
00408603 837DF801 cmp dword ptr [ebp-$08],$01
00408607 7503 jnz $0040860c
00408609 FF45F4 inc dword ptr [ebp-$0c]
Project5.dpr.19: end; //all vars stay in scope.
0040860C 8BE5 mov esp,ebp //until the stack frame is dismantled.
0040860E 5D pop ebp
0040860F C3 ret
因此,关闭优化绝不会发生您的情况,但是...
您也可以在源代码中设置优化的开/关:
{$Optimization on/off} or
{$O+/-}
如果该行位于例程的前面,它将覆盖全局设置。
http://docwiki.embarcadero.com/RADStudio/zh/Optimization_%28Delphi%29
, 您发布的代码无法按原样编译,因此我不能100%没有通过我的个人修改来杀死复制案例以使其运行……但是我无法复制您的特定问题。还有谁可以吗?
当然,当优化打开时,调试器/评估器会抱怨,但是随着优化的关闭和重建,问题肯定消失了。您确定您进行了适当的重建吗?
我有点不同意戴维斯的说法,即“我们所有人都会不时遭受这种痛苦”。除了已知的和可预测的边界情况(变量超出范围,断点在末端)之外,我实际上从未遇到过此问题。只要我阻止我的同事将dproj检查到启用了优化的版本控制即可。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。