2
votes

I compiled a dll with MinGW. For that I used commands below:

gcc -shared -o MathsDll.dll MathsDll.c -Wl,--output-def,MathsDll.def,--out-implib,libMathsDll.a

lib /machine:i386 /def:MathsDll.def

Then I try to use that dll from a C code. My command for compiling is below:

cl mainCode.c MathsDll.lib

It worked for that situation but when I change my mainCode.c file to mainCode.cpp I am taking error:

mainCode.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) int _cdecl add(int,int)" (_imp_?add@@YAHHH@Z) referenced in function _main mainCode.exe : fatal error LNK1120: 1 unresolved externals

Why that dll working in a C code but C++?

By the way I used MinGW's web site for reference. http://www.mingw.org/wiki/MSVC_and_MinGW_DLLs

mainCode.cpp:

#include <stdio.h>
#include "MathsDll.h"

int main()
{
printf("%d",add(3,4));
}

MathsDll.h:

#ifdef MATHDLL_EXPORTS
#define MATHDLL_API extern "C" __declspec(dllexport) 
#else
#define MATHDLL_API __declspec(dllimport) 
#endif

MATHDLL_API int add(int,int);
MATHDLL_API int multiply(int,int);

MathsDll.c / MathsDll.cpp:

#include "MathsDll.h"

int add(int a,int b)
{
    return a+b;
}

int multiply(int a,int b)
{
    return a*b;
}
1

1 Answers

2
votes

If you have functions in a DLL written in C that you want to access from a C language or C++ language module, you should use the __cplusplus preprocessor macro to determine which language is being compiled, and then declare these functions with C linkage if being used from a C++ language module.

http://msdn.microsoft.com/en-us/library/ys435b3s.aspx