Search code examples
c++operating-systemkernelosdev

Static constructors in C++ on my own OS kernel


I am trying to write a kernel in c++ and I am a beginner in OS development. Now I am implementing cout to display on a monitor, but I am facing some problems. I know the question I am asking is foolish, but I am a newbie in c++ as well.

I have written an OStream class which calls the system function write to display on the screen. Its base class is my Video class. This class is included into namespace std. So the main problem is that when I create a object of OStream, it is not calling it's constructor and hence not calling the constructor of its base class, so that videomemory is not initialising and therefore nothing will be displayed on screen.

Here is my code:

/*OStream.h*/
namespace std{
class OStream:public Video{
    public:
    OStream();
    OStream& operator<<(int);
    OStream& operator<<(String);
    OStream& operator<<(char *cp);
    OStream& operator<<(char c);
    OStream& operator<<(unsigned char *cq);
    OStream& operator<<(unsigned char c1);
};
extern OStream cout;
}

/*OStream.cpp*/
namespace std{
    OStream cout;
    OStream::OStream(){}
    OStream& OStream::operator<<(char *cp){
        write(cp);
    }
    .
    . 
    .
    .
}

In the above code I am creating an object of OStream class in the OStream.cpp file itself. But if I create an object in my main module then it calls its constructor successfully, but then cout is not working.

That means if I create an object explicitly it works perfectly, but how can I create an object implicitly.

And same thing is happening with my Interrupt.cpp module.

So please help me to solve this type of problem. Please help me. Any help will be appreciated. Thank you.


Solution

  • First, your implementation of cout is non-conforming. If you're going to be writing a C++ standard library, you must write it to be conforming to said standard (not to what you think the standard is).

    Second, you need to implement static constructor support. You haven't specified your compiler, so all I can say is figure out where your compiler puts its static constructor initialization code, and make sure to invoke it on program startup.

    You may have more luck adapting existing C++ libraries (GCC's libstdc++ or clang's libc++) to your new OS than writing one from scratch. Writing a C++ stdlib is NOT something for a beginner; you'll be neck-deep in template metaprogramming in no time.