I have a DLL using some <Windows.h> functions that I'd like to make compatible with Linux. I know there are Linux equivalents for these functions and I could easily use an #ifdef , compile for Linux and have two versions of the DLL, but I'd like to have one DLL that can be used on both machines.
Is there a way I can tell what operating system is present when I run the DLL? Something like:
1 2
if (Linux) LinuxCommands();
elseif (Windows) WindowsCommands();
If it makes a difference, the OS-specific code looks like:
1 2 3 4 5 6 7 8 9 10
#include <Windows.h> //I don't seem to need <ctime> if <Windows.h> is called.
//Time computations
struct tm LocalTime;
__time32_t aclock;
_time32( &aclock ); // Get time in seconds.
_localtime32_s( &LocalTime, &aclock ); // Convert time to struct tm form.
//Set console colour
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
When looking at forums, the time functions really don't appear to be OS-specific. However, <ctime> includes <time.h> which has the following line in it:
1 2 3
#if !defined(_WIN32)
#error ERROR: Only Win32 target supported!
#endif
To me, this means that it isn't going to work in Linux at all, unless this header file was written by Microsoft and Linux compilers comes with different headers all together. (I'm using VS2010 on Windows 7).
If you stick to C and C++ standard libraries, you can be confident that your code will be portable across platforms. However, if you use platform specific libraries, then you'd expect those parts to work only on that platform.
Third party libraries can help. For example, if you wanted to create a portable GUI app, it would be sensible to use a GUI library that supported the platforms you were targeting.
In your examples, it seems you've gone out of your way to find Windows specific code, whereas you'll find the Linux code is portable.
Hmm interesting, so the funny define I saw in my second post will not make the file exclusive to Windows? That is good news.
I've tried using the Linux method of cout << "\033[1;31mRED TEXT HERE\n" in Windows, but I don't get a change in text colour. In some forums I've ready that this method doesn't work with all Linux shells either. This part does appear to be very OS-specific. If Linux uses the same commands, perhaps I could try system("color 1F") but I don't think that's a good idea.
You could have source code that will compile into both a windows dll and a linux so, I'm going to assume that's what you mean.
The technique I know of, is to have an abstract base class for your interface to all of the required functions. Before use, instantiate the platform specific concrete class for your current platform.
You can do the same in C with a struct of function pointers, but it's not as neat.