views:

126

answers:

2

I've been going through the dll walkthrough on MSDN and it works fine. I then removed all the C++ style code in the dll and replaced it with the C equivalent, and it still works.

BUT, when I rename the file from X.cpp to X.c (which I guess causes compilation in C-mode), I get error LNK2019 (unresolved external symbol) for every function in the dll. For my purposes it's essential that the dll be in C not C++ because that's what Java Native Access supports.

Here's the header of the dll:

__declspec(dllexport) double Add(double a, double b);
__declspec(dllexport) double Subtract(double a, double b);
__declspec(dllexport) double Multiply(double a, double b);
__declspec(dllexport) double Divide(double a, double b);

Here's the body of the (C++) testing program that uses the dll:

#include <iostream>
#include "MyMathFuncs.h"
using namespace std;
int main()
{
    double a = 7.4;
    int b = 99;

    cout << "a + b = " <<
        Add(a, b) << endl;
    cout << "a - b = " <<
        Subtract(a, b) << endl;
    cout << "a * b = " <<
        Multiply(a, b) << endl;
    cout << "a / b = " <<
        Divide(a, b) << endl;

    return 0;
}

(Just to clarify it's fine that the testing program is in C++; it's only the dll I'm trying to compile in C).

+4  A: 

Add

extern "C"
{
#include "MyMathFuncs.h"
}
Tuomas Pelkonen
or better put the extern "C" in the header file
Mark
Yes, you can do the #ifdef __cplusplus extern "C" thing in the header
Tuomas Pelkonen
Awesome thank you! The file does now compile with the dll source file called X.c.And yet JNA still can't load the dll correctly :(I'll post that as a separate issue when I have more information.
Yuvi Masory
+1  A: 

After you changed the extension, you are now using the wrong names in the client code. Those names are no longer decorated as they were when you compiled it as C++ code. The proper way to export names like this, so that those decorations are never used and you don't depend on the language:

extern "C" __declspec(dllexport)
double Add(double a, double b);

To see the exported names, use Dumpbin.exe /exports on your DLL.

Hans Passant