gpt4 book ai didi

c - 写入视频内存(0xB8000)和 volatile 指针

转载 作者:太空狗 更新时间:2023-10-29 16:11:34 25 4
gpt4 key购买 nike

我正在尝试用 C 编写自己的小内核,实际上我想编写一个打印函数来显示字符串。因此,我想写入视频内存(位于0xB8000)。

所以,我这样试过:

unsigned char *video = (unsigned char *)0xB8000;

*video = 'A';

这确实有效,但以下内容无效:

char x = 0;
unsigned char *video = (unsigned char *)(0xB8000 + x);

*video = 'A';

经过一些研究,我认为原因可能是编译器的优化,OSDev给我解决方案:使用 volatile 关键字。所以我对这个关键词做了一些研究。 OSDev 建议:

char x = 0;
volatile unsigned char *video = (volatile unsigned char *)(0xB8000 + x);

*video = 'A';

这样,它应该可以工作。编译器假定video 指针指向的值可以改变,因此不对其进行优化。但是,如果以后我想更改它,例如:

video = (volatile unsigned char *)(video + 2);

我不应该将指针定义为volatile,比如unsigned char * volatile video吗?所以编译器知道地址可以改变?

最佳答案

volatile 的要点是告诉编译器变量的内容可能会改变或在代码执行之外产生副作用。作为standard (C99 6.7.3.6) 说:

An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Therefore any expression referring to such an object shall be evaluated strictly according to the rules of the abstract machine, as described in 5.1.2.3. Furthermore, at every sequence point the value last stored in the object shall agree with that prescribed by the abstract machine, except as modified by the unknown factors mentioned previously. What constitutes an access to an object that has volatile-qualified type is implementation-defined.

这就是为什么你需要告诉编译器变量指向的内存是易失的。但是,更改指针指向的地址不会导致任何副作用,并且不会在代码执行之外自行更改,因此指针本身没有理由易变。如果我们必须将我们希望在某个时候更改的所有变量标记为 volatile,那么几乎所有变量都必须这样标记。

关于c - 写入视频内存(0xB8000)和 volatile 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32221707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com