Skip to main content
edited tags; edited title
Link
200_success
  • 145.6k
  • 22
  • 191
  • 480

Better way to use Macro Function declarations using macros to support multiple platforms

Source Link
Programmer
  • 255
  • 2
  • 7

Better way to use Macro to support multiple platforms

I wrote a C++ plugin that retrieves screen pixel. It works on Windows and Android. I noticed that dllexport is only required on Windows but not on Android and causes error on other platform other than Windows. I fixed that by using #if macro to make it use dllexport only on Windows.

Here is the fixed header code:

#ifndef ANDROIDSCREENSHOT_NATIVE_LIB_H
#define ANDROIDSCREENSHOT_NATIVE_LIB_H

#define DLLExport __declspec(dllexport)

extern "C"
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
DLLExport void initScreenPointPixel(void* buffer, int x, int y, int width, int height);
DLLExport void updateScreenPointPixelBufferPointer(void* buffer);
DLLExport void updateScreenPointPixelCoordinate(int x, int y);
DLLExport void updateScreenPointPixelSize(int width, int height);
int GetScreenPixels(void* buffer, int x, int y, int width, int height);

#else
void initScreenPointPixel(void *buffer, int x, int y, int width, int height);
void updateScreenPointPixelBufferPointer(void *buffer);
void updateScreenPointPixelCoordinate(int x, int y);
void updateScreenPointPixelSize(int width, int height);
int GetScreenPixels(void *buffer, int x, int y, int width, int height);
#endif
}
#endif //ANDROIDSCREENSHOT_NATIVE_LIB_H

It works and fixes the problem but I don't like the fact that I have to declare each of these functions twice. Once in the #if and another in the #else statement. I have many functions if not thousands and if I go this route, the code would be unnecessary long. The simple goal is to remove dllexport on non Windows platform without declaring the function twice like I am currently doing.

Is there a better way to do this with macro without having to declare each function again? Any solution without macros is also good as long as I don't have to declare each function multiple times.