Question

I am working under Arch Linux and using GCC as my compiler. I am wondering, if I want to make a cross compatible program -- now I'm not talking a gui-based program -- I'm just asking in general. How would I be able to implement cross compatible structure such as windows.h in Linux, Mac Osx, and windows at the same time?

Was it helpful?

Solution

In terms of things like <windows.h> - you don't. Or at least, you try not to.

If you do end up needing to use a GUI, you'll want to look into something cross-platform (I'm fairly sure Qt has good cross-platform support, wxWidgets might as well). Either way, your goal is to write as much standard C++ code as possible and invoke as few system libraries/APIs as possible.

If you do end up needing to use system APIs, wrap them in functions, and use #ifdefs within those functions to ensure you're calling the right API. Generally your compiler will provide a few macros that will let you determine which OS you're running on, to a certain extent, as well as 32-bit vs 64-bit.

void DoSomething()
{
  #ifdef _WIN32
  //do Windows things here
  #endif

  #ifdef __linux__
  //do Linux things here
  #endif
}

Or:

void DoSomethingWindows()
{
  //private Windows code here
}

void DoSomethingLinux()
{
  //private Linux code here
}

void DoSomething()
{
  #ifdef _WIN32
    DoSomethingWindows();
  #endif

  #ifdef __linux__
    DoSomethingLinux()
  #endif
}

If you really want to get fancy, you could even set up entire headers for your platform-specific code. Just use #ifdefs to figure out your target OS and #include accordingly.

Also, make sure you do a lot of testing on all systems involved. System APIs won't necessarily have perfect matches across different operating systems, and if you make assumptions about the way a given API acts but don't test it, you might find yourself in trouble down the road.

OTHER TIPS

The strategy can be as follows: encapsulate all platform-specific code in classes and typedefs and write code which will work with these classes interfaces. These areas are usually: files, threads, basic types sizes. In these classes write platform-specific code using #ifdef.

#ifdef _WIN32
//...
#else
//...

Thus you can then easily add another target platform.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top