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 worki开发者_如何学Gong.
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.
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.
It's not possible to create an object without calling it's constructor. But with global variables like cout
sometimes the time that the constructor gets called is a problem. If you have two global variables in different .cpp files then you cannot predict which global variable will get constructed first. Maybe that is the problem you are seeing? If so then the easy answer is to put all your global variables into one .cpp file (call it globals.cpp if you like). Then the global variables will get constructed in the order that you declare them within that .cpp file (and destructed in the reverse order).
精彩评论