如何使用预处理器创建跨平台库?

App*_*ker 5 c++ graphics platform cross-platform c-preprocessor

我想使用#ifdefWxWidgets,SDL等使用的相同方法.唯一的问题是我不知道如何使用它.

假设我想创建一个绘制矩形的类.我希望它在X11平台(即linux)和win32平台上的GDI上使用cairo:

class graphics
{
void drawRect(int x, int y, int w, int h)
{
/*if on win32*/
HDC myHdc = ::BeginPaint(myHwnd,&mypstr);
::Rectangle(myHdc,x,y,w,h); 
::EndPaint(myHwnd,&mypstr);

/*if on x11*/
cairo_surface_t* s = cairo_xlib_surface_create(/* args */); 
cairo_t* c = cairo_create(s);
cairo_rectangle(c,x,y,w,h);
// etc. etc.
}
};
Run Code Online (Sandbox Code Playgroud)

我将如何使用#ifdef或其他东西来做这件事?

Tho*_*ews 3

如果可以的话,最好将平台特定的方法放入单独的翻译单元中。这将使代码更清晰、更易读,并且更容易开发和维护。恕我直言,构建过程应该确定要合并哪些平台特定模块。

例如:
矩形.hpp:

struct Rectangle
{
  void draw(int upper_left_corner_x, int upper_left_corner_y,
            unsigned int length, unsigned int width);
}
Run Code Online (Sandbox Code Playgroud)

现在是平台特定文件:
矩形_wx_widgets.cpp:

#include "rectangle.hpp"
void
Rectangle ::
draw(int upper_left_corner_x, int upper_left_corner_y,
            unsigned int length, unsigned int width)
{
// wxWidgets specific code here.
}
Run Code Online (Sandbox Code Playgroud)

矩形_qt.cpp:

#include "rectangle.hpp"
void
Rectangle ::
draw(int upper_left_corner_x, int upper_left_corner_y,
            unsigned int length, unsigned int width)
{
// QT specific code here.
}
Run Code Online (Sandbox Code Playgroud)

主要.cpp:

#include "rectangl.hpp"
int main(void)
{
  Rectangle r;
  r.draw(50, 50, 10, 5);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码没有条件预处理器指令。main无论平台如何,该函数都会绘制一个矩形。该平台的细节已被删除,main因为它们并不重要。因此,无需更改任何编译器开关或担心定义了哪个预处理器标识符,我们就可以看到main无条件地绘制了一个矩形。

要使用 wxWidgets 平台进行绘制,构建过程将使用rectangle_wx_widgets.cpp. 要使用 QT 进行绘图,rectangle_qt.cpp将使用该文件,但不能同时使用两者。如图所示,无需更改任何代码即可为任一平台生成代码。人们可以定制构建过程,以便命令build wxWidgets包含正确的翻译单元。因此,将参数传递给构建过程会生成特定于平台的可执行文件。