Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating shared and static libraries using g++ (under Windows)

How do I create static and dynamic libraries for Windows using g++?

I've found a few commands for Linux for creating .so files and I've tried to apply them on a Windows shell, but they build .dll files that my applications fail to link with at runtime.

I've only managed to build .dll files using Visual C++ but I would like to build them manually on the command line, preferably using g++. I would also like to know how to build static libraries too for Windows.

like image 933
Barbel Zeus Bryo Avatar asked Apr 24 '26 11:04

Barbel Zeus Bryo


1 Answers

You need to prefix with the attribute :

__declspec(dllexport)...

all the features you want to expose.

See this.

Example for a C function:

__declspec(dllexport) int __cdecl Add(int a, int b)
{
  return (a + b);
}  

This can be simplified using MACROS: everything is explained on this helpful page.


For C++ classes, you only need to prefix each class (not every single method)

I usually do it that way :

Note : The following also ensures portability...

Include File :

// my_macros.h
//
// Stuffs required under Windoz to export classes properly
// from the shared library...
// USAGE :
//      - Add "-DBUILD_LIB" to the compiler options
//
#ifdef __WIN32__
#ifdef BUILD_LIB
#define LIB_CLASS __declspec(dllexport)
#else
#define LIB_CLASS __declspec(dllimport)
#endif
#else
#define LIB_CLASS       // Linux & other Unices : leave it blank !
#endif

Usage :

#include "my_macros.h"

class LIB_CLASS MyClass {
}

Then, to build, simply :

  • Pass the option -DBUILD_LIB to the usual compiler command line
  • Pass the option -shared to the usual linker command line
like image 109
Gauthier Boaglio Avatar answered Apr 27 '26 00:04

Gauthier Boaglio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!