Skip to content

Instantly share code, notes, and snippets.

@baptistelabat
Last active March 27, 2022 12:50
Show Gist options
  • Save baptistelabat/b1457e5eec7f2d1192ba99240cb270cc to your computer and use it in GitHub Desktop.
Save baptistelabat/b1457e5eec7f2d1192ba99240cb270cc to your computer and use it in GitHub Desktop.
How to compile and access a c++ dll from c++ (taken from http://www.mingw.org/wiki/sampledll)
rem You need to have g++ and gfortran installed (for example, use MinGW and add the bin repertory to your path).
rem Build the example_dll.dll
g++ -c -DBUILDING_DLL example_dll.cpp
rem .a is needed for gfortran compiler
g++ -shared -o example_dll.dll example_dll.o -Wl,--out-implib,libexample_dll.a
rem .lib is needeede by ifort compiler (but it is the same file)
copy libexample_dll.a libexample_dll.lib
rem del libexample_dll.a
rem del libexample_dll.lib
rem Build the gpp_exe.exe
g++ -c example_exe.cpp
g++ example_exe.o -L. -lexample_dll -o gpp_exe.exe
rem Build the gfortran_exe.exe
gfortran -c example_exe.f90 -o example_exe.o
gfortran example_exe.o -L. -lexample_dll -o gfortran_static_exe.exe -static
gfortran example_exe.o example_dll.dll -L. -o gfortran_exe.exe
rem Test the resulting exe
gpp_exe
rem If compilation is static, it will run alone
gfortran_static_exe
rem If compilation is not static you need to add gfortran dll (libgfortran-3.dll, etc) to your path.
gfortran_exe
rem Build the ifort_exe.exe
rem You need to run the following command to set up intel correctly
rem "C:\Program Files (x86)\Intel\Composer XE 2015\bin\compilervars.bat" ia32 vs2015
ifort -c example_exe.f90 -o example_exe.o
ifort example_exe.o /link libexample_dll.lib /out:ifort_exe.exe
ifort_exe
del *.o
del *.obj
g++ -o example_exe.exe example_exe.o -L. -lexample_dll
example_exe
pause
#include <stdio.h>
#include "example_dll.h"
int ComputeDouble(int x)
{
return 2 * x;
}
#ifndef EXAMPLE_DLL_H
#define EXAMPLE_DLL_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef BUILDING_DLL
#define DLL_EXPORT_OR_IMPORT __declspec(dllexport)
#else
#define DLL_EXPORT_OR_IMPORT __declspec(dllimport)
#endif
int DLL_EXPORT_OR_IMPORT ComputeDouble(int x);
#ifdef __cplusplus
}
#endif
#endif // EXAMPLE_DLL_H
#include <stdio.h>
#include "example_dll.h"
int main(void)
{
printf("%d\n", ComputeDouble(11));
return 0;
}
!example_exe.f90
program example_exe
implicit none
interface
function ComputeDouble(a) result(b) bind(C, name='ComputeDouble')
use iso_c_binding
implicit none
Integer(c_int), value :: a
integer:: b
end function ComputeDouble
end interface
! This is the main program
integer::b
b = ComputeDouble(11)
print*,b ! Should display 22
end program example_exe
@ClurCode
Copy link

Oh man so thank u, i want this for a lot time. U really save me.
And i'm sry for my english i'm argentinian, and i don't know if i said something bad aajaj

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment