In Visual Studio 2008, using C++, I tried to build a DLL using the instructions at http://msdn.microsoft.com/en-us/library/ms235636.aspx, except I named a source file with an extension of “.c” rather than the suggested “.cpp”.
With an extension of .c, the compiler throws 37 errors. With an extension of .cpp, the DLL builds successfully.
What difference does the extension of a source file make?
Here is the full code:
// MathFuncsDll.cpp
// compile with: /EHsc /LD
#include "MathFuncsDll.h"
#include <stdexcept>
using namespace std;
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}
return a / b;
}
}
// MathFuncsDll.h
namespace MathFuncs
{
class MyMathFuncs
{
public:
// Returns a + b
static __declspec(dllexport) double Add(double a, double b);
// Returns a - b
static __declspec(dllexport) double Subtract(double a, double b);
// Returns a * b
static __declspec(dllexport) double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
static __declspec(dllexport) double Divide(double a, double b);
};
}
The compiler (driver program) guesses at the source language based on the extension, assuming C for
.cand C++ for.cpp. You can override that guess with-Tpto force C++ or-Tcto force C. If you want that for all the files you pass instead of just one, capitalize (-TPor-TC).