samedi 20 octobre 2018

Handling platform-dependent behavior using #ifdefs in source files?

I am developing software that will run on multiple platforms. I provide a general header file that includes all public API functions. The actual source files will contain very different code depending on the platform it is compiled for.

I could handle all platforms in the same .cpp-file, but I feel like that will get messy really really fast.

The next idea was, to have a source-file per platform, surrounded by #ifdefs that contains the platform specific code. I feel like this is a much cleaner way, because the wrong code basically doesn't even exist on the wrong platform. I am obviously not looking for the BEST way because that's very subjective.

  1. Is this an acceptable way of handling platform-dependent code or am I committing a major mistake that I am missing?
  2. Would you find code like this in medium to high quality code-bases?
  3. Are there any major drawbacks to this method?

Window.h:

#pragma once
class Window
{
    public:
        void Create();
};

Window_Win32.cpp:

#ifdef WINDOWS
#include "Window.h"

void Window::Create()
{
    // Win32 specific
}
#endif

Window_Linux.cpp:

#ifdef LINUX
#include "Window.h"

void Window::Create()
{
    // Linux specific
}
#endif

Aucun commentaire:

Enregistrer un commentaire