I need some help on writing cross-platform code; not an application, but a library.
I am creating a library both static and dynamic with most of the development done
You can pretty easily do it with #ifdef's. On Windows _WIN32 should be defined by the compiler (even for 64 bit), so code like
#ifdef _WIN32
# define EXPORTIT __declspec( dllexport )
#else
# define EXPORTIT
#endif
EXPORTIT int somefunction();
should work OK for you.
Maybe it's better if you Add extern "C" !!!,
/* file CMakeLists.txt */
SET (LIB_TYPE SHARED)
ADD_LIBRARY(MyLibrary ${LIB_TYPE} MyLibrary.h)
/* file MyLibrary.h */
#if defined(_WIN32) || defined(__WIN32__)
# if defined(MyLibrary_EXPORTS) // add by CMake
# define MYLIB_EXPORT extern "C" __declspec(dllexport)
# else
# define MYLIB_EXPORT extern "C" __declspec(dllimport)
# endif // MyLibrary_EXPORTS
#elif defined(linux) || defined(__linux)
# define MYLIB_EXPORT
#endif
MYLIB_EXPORT inline int Function(int a) {
return a;
}
In general, there are two issues you need to be concerned with:
__declspec(dllexport)
, andFor the first, you will need to learn about __declspec(dllexport)
. On Windows only projects, typically this is implemented in the way I describe in my answer to this question. You can extend this a step further by making sure that your export symbol (such as MY_PROJECT_API) is defined but expands to nothing when building for Linux. This way, you can add the export symbols to your code as needed for Windows without affecting the linux build.
For the second, you can investigate some kind of cross-platform build system.
If you're comfortable with the GNU toolset, you may want to investigate libtool (perhaps in conjunction with automake and autoconf). The tools are natively supported on Linux and supported on Windows through either Cygwin or MinGW/MSYS. MinGW also gives you the option of cross-compiling, that is, building your native Windows binaries while running Linux. Two resources I've found helpful in navigating the Autotools (including libtool) are the "Autobook" (specifically the section on DLLs and Libtool) and Alexandre Duret-Lutz's PowerPoint slides.
As others have mentioned, CMake is also an option, but I can't speak for it myself.