简体   繁体   English

不能在 gcc 中使用全局变量

[英]Can't use global variables with gcc

I have a file like this:我有一个这样的文件:

char* vidmem = (char*)0xb8000;

int main()
{
    vidmem[0] = 'x';
    vidmem[1] = 0x0f;
}

But when i compile it with gcc it behave like vidmem does not even exist.但是当我用 gcc 编译它时,它的行为就像 vidmem 甚至不存在一样。 I have this problem with all variable declared outside of function.我在函数外声明的所有变量都有这个问题。 Maby this one can be declare inside main but other variables in other files linked to this can't be. Maby 这个可以在 main 中声明,但其他文件中的其他变量不能声明。 This how I compile it:这是我编译它的方式:

gcc -c main.c -o main.obj -ffreestanding -fno-exceptions -m64

And this is how i assemble all the files:这就是我组装所有文件的方式:

gcc -m64 -Wl,--build-id=none -static -fno-asynchronous-unwind-tables -nostdlib -nodefaultlibs -lgcc main.obj [..] -T linker.ld -o out.bin

Why this happen?为什么会发生这种情况? And how can i solve it?我该如何解决?

EDIT:编辑:

I am making an OS and this is the code from the C kernel.我正在制作一个操作系统,这是来自 C 内核的代码。 I am using linux subsystem for windows to compile it and qemu for testing我正在使用 windows 的 linux 子系统来编译它,并使用 qemu 进行测试

Here is a link to all the code: http://www.mediafire.com/file/7x21lh4dnc93dz9/OS.7z/file这是所有代码的链接: http : //www.mediafire.com/file/7x21lh4dnc93dz9/OS.7z/file

You can declare global variables but you have to initialize inside main like this: char* vidmem;您可以声明全局变量,但必须像这样在 main 内部进行初始化: char* vidmem;

char* vidmem;

int main()
{
    vidmem = (char*)0xb8000;

    vidmem[0] = 'x';
    vidmem[1] = 0x0f;
}

I don't understand why there are so many down votes to this question.我不明白为什么这个问题有这么多反对票。 This is a totally valid and interesting question and I just ran into the same problem 1 hour ago.这是一个完全有效且有趣的问题,我在 1 小时前遇到了同样的问题。

The problem is that in a normal scenario when the linker is generating an executable to run on Linux, for example, the global variables are stored in the .data section, and their values are part of the executable.问题是,在正常情况下,例如,当链接器生成要在 Linux 上运行的可执行文件时,全局变量存储在 .data 部分中,它们的值是可执行文件的一部分。 Now, in your scenario, you are generating raw binary data and directly booting it.现在,在您的场景中,您正在生成原始二进制数据并直接启动它。 In this case, you need to specify to the linker where the global variables should be stored in the image.在这种情况下,您需要向链接器指定全局变量应存储在映像中的位置。 You can do it via -Tdata 0x6000 to store them starting at address 0x6000, for example.例如,您可以通过-Tdata 0x6000将它们存储在地址 0x6000 处。 Then, when loading your OS, be sure to load this part of the image to memory, before accessing the global variable.然后,在加载操作系统时,请确保在访问全局变量之前将这部分图像加载到内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM