# Function declarations using macros 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 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);
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.

Keep the DLLExport macro on all platforms, but make the definition resolve to nothing unless you're on Windows. You might also want to rename the macro to something more neutral. Something like this:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
# define EXPORT __declspec(dllexport)
#else
# define EXPORT
#endif

extern "C"
{
EXPORT void initScreenPointPixel(void* buffer, int x, int y, int width, int height);
}


You should also be aware of that the extern "C" stuff is only recognized by a C++ compiler. The related statements should also be conditional, e.g.:

#ifdef __cplusplus
extern "C" {
#endif

... declarations here

#ifdef __cplusplus
}
#endif

• "You should also be aware of that the extern "C" stuff is only recognized by a C++ compiler. " I know. That's why I tagged C++ in this question and also mentioned it in the first sentence of my question. It's a C++ plugin that uses C++ features and syntax that can never be compiled on C. – Programmer Apr 13 '18 at 7:59