我正在编写自己的操作系统内核,并开始使用 C++ 进行打印功能。我可以用字符打印到 VGA 内存(0xB8000),但是当我使用
print_str(const char* str)
函数时,它只会在屏幕上打印三个随机符号(无论字符串的大小和值如何,它都会打印相同的三个随机符号) :
这些是我的
print_char
和 print_str
功能:
void print_char(const char character) {
Char* buffer = reinterpret_cast<Char*>(VGA_ADDRESS);
// Handeling new line character input
if(character == '\n') {
print_newline();
return;
}
if(col >= NUM_COLS) {
print_newline();
}
buffer[col + NUM_COLS * row] = {static_cast<uint8_t>(character), color};
col++; // Incrementing character number on this line
}
// Printing string to the screen
void print_str(const char* str) {
// Calling the print_char function the same amount of times as the strings length
for(size_t i = 0; str[i] != '\0'; i++) {
print_char(str[i]);
}
}
还有我的链接器脚本(如果需要):
OUTPUT_FORMAT("binary")
OUTPUT_ARCH(i386)
ENTRY(_start)
SECTIONS
{
/* Bootloader section at 0x7C00 (BIOS loads the bootloader here) */
. = 0x7C00;
.boot : {
*(.boot) /* Include all .boot sections */
*(.text) /* Include all .text sections for bootloader code */
}
/* Align to 1 MiB (where kernel starts) */
. = 0x100000;
/* Kernel sections */
.text : ALIGN(4096)
{
__kernel_start = .; /* This is the start address of the kernel */
*(.text)
}
.rodata : ALIGN(4096)
{
*(.rodata)
}
.data : ALIGN(4096)
{
*(.data)
}
.bss : ALIGN(4096)
{
*(COMMON)
*(.bss)
}
__kernel_end = .; /* This is the end address of the kernel */
}
VGA 文本模式的内存由每个字符 16 位或 2 个字节组成。标准的 c/c++ char 是 8 位,即 1 个字节。 VGA 文本模式下的字符由包含特殊信息的字节组成,例如前景色、背景色以及字符是否闪烁。在该字节之后,有一个字符字节。这意味着标准字符不能用于在 vga 文本模式缓冲区上写入。 您可以在关于 VGA 文本模式的维基百科上阅读更多信息。 OSDev Wiki 还有一篇关于 vga 的精彩文章。