Reputation: 9235
I am attempting to build an OS layer in a project, to provide OS-independent functions to other source codes. For example, I might have functions like os_calloc, os_free, etc. I don't think those are very OS-dependent, but feel free to think of better examples.
Currently we have a system that's set up like so:
#ifdef WINDOWS
void * os_calloc(){
//Windows implementation
}
void * os_free(){
//Windows implementation
}
#endif
#ifdef LINUX
void * os_calloc(){
//Linux implementation
}
void * os_free(){
//Linuximplementation
}
#endif
Now, this doesn't sit right to me. The main reason is that in theory we want to define a set of OS-independent functions and have the exact same set on every system, just with different implementations.
Can this strict relationship be enforced through any programming patterns? That is, the rule saying "each os implementation must implement this set of functions, no more no less".
EDIT: Let me just make it clear that I'm asking how this relationship can be enforced through design/programming patterns, not for links to other OS-independent libraries.
Upvotes: 1
Views: 121
Reputation: 7834
If you want to enforce something then create an interface class called "IOsInterface" (or similar) that describes the required interface. Any actual OS implementations must fulfill this contract, ie. inherits from the interface class and implements all of the virtual methods.
class IOsInterface
{
public:
virtual ~IOsInterface() {}
virtual void * calloc() = 0;
};
class OsWindowsImpl : public IOsInterface
{
public:
virtual void * calloc()
{
//Windows implementation
}
};
Create a single instance (Singleton, you can't do static virtuals) and use that as the programmatic interface for functionality that uses the OS methods.
Having worked with a home-grown OS-independence layer (Windows, Linux, Solaris Sparc, Solaris X86, and both 32- and 64-bit implementations of each), however, please consider what you are doing very carefully... :-) Boost, QT, APR, all of those are very viable options. Only if your company has a strict policy that everything must be created in-house is this a good idea, I think.
Upvotes: 1
Reputation: 137398
Yes, it can work like this. But why invent the wheel? This is what the Apache Portable Runtime does. (The site appears to be down right this minute.) Some OS-independent things APR provides (from Wikipedia):
Upvotes: 1
Reputation: 1
There are already C++ libraries providing that. For example QtCore part of Qt
Upvotes: 1