Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self contained C routine to print string

I would like to make a self contained C function that prints a string. This would be part of an operating system, so I can't use stdio.h. How would I make a function that prints the string I pass to it without using stdio.h? Would I have to write it in assembly?

like image 892
user2151887 Avatar asked Mar 09 '13 16:03

user2151887


2 Answers

Assuming you're doing this on an X86 PC, you'll need to read/write directly to video memory located at address 0xB8000. For color monitors you need to specify an ASCII character byte and an attribute byte, which can indicate color. It is common to use macros when accessing this memory:

#define VIDEO_BASE_ADDR    0xB8000
#define VIDEO_ADDR(x,y)    (unsigned short *)(VIDEO_BASE_ADDR + 2 * ((y) * SCREEN_X_SIZE + (x)))

Then, you write your own IO routines around it. Below is a simple function I used to write from a screen buffer. I used this to help implement a crude scrolling ability.

void c_write_window(unsigned int x, unsigned int y, unsigned short c)
{
  if ((win_offset + y) >= BUFFER_ROWS) {
    int overlap = ((win_offset + y) - BUFFER_ROWS);
    *VIDEO_ADDR(x,y) = screen_buffer[overlap][x] = c;
  } else {
    *VIDEO_ADDR(x,y) = screen_buffer[win_offset + y][x] = c;
  }
}

To learn more about this, and other osdev topics, see http://wiki.osdev.org/Printing_To_Screen

like image 141
Mr. Shickadance Avatar answered Nov 04 '22 01:11

Mr. Shickadance


You will probably want to look at, or possibly just use, the source to the stdio functions in the FreeBSD C library, which is BSD-licensed.

To actually produce output, you'll need at least some function that can write characters to your output device. To do this, the stdio routines end up calling write, which performs a syscall into the kernel.

like image 28
sfstewman Avatar answered Nov 04 '22 02:11

sfstewman