我仍在学习 C++ 语言的一些用途。
因此,我决定创建我的库(动态)并将其导入到我的项目中。我已经按照互联网上教程的一些步骤进行操作,但是我遇到了未解决的外部错误...
让我去DLL项目:
文件 1.cpp:
#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 invalid_argument("b cannot be zero!");
}
return a / b;
}
}
MathFuncs.h:
#ifdef MATHFUNCSDLL_EXPORTS
#define MATHFUNCSDLL_API __declspec(dllexport)
#else
#define MATHFUNCSDLL_API __declspec(dllimport)
#endif
namespace MathFuncs
{
// This class is exported from the MathFuncsDll.dll
class MyMathFuncs
{
public:
// Returns a + b
static MATHFUNCSDLL_API double Add(double a, double b);
// Returns a - b
static MATHFUNCSDLL_API double Subtract(double a, double b);
// Returns a * b
static MATHFUNCSDLL_API double Multiply(double a, double b);
// Returns a / b
// Throws const std::invalid_argument& if b is 0
static MATHFUNCSDLL_API double Divide(double a, double b);
};
}
结果:成功编译(得到 Project1.dll 和 Project1.lib 文件)。
使用以下详细信息启动了一个新的控制台应用程序:
文件 1.cpp:
// MyExecRefsDll.cpp
// compile with: /EHsc /link MathFuncsDll.lib
#include <iostream>
#include <Windows.h>
#include "MathFuncsDll.h"
using namespace std;
int main()
{
double a = 7.4;
int b = 99;
try {
LoadLibrary(TEXT("MathFuncsDll.dll")); // Also tried without TEXT();
cout << "a + b = " <<
MathFuncs::MyMathFuncs::Add(a, b) << endl;
cout << "a - b = " <<
MathFuncs::MyMathFuncs::Subtract(a, b) << endl;
cout << "a * b = " <<
MathFuncs::MyMathFuncs::Multiply(a, b) << endl;
cout << "a / b = " <<
MathFuncs::MyMathFuncs::Divide(a, b) << endl;
try
{
cout << "a / 0 = " <<
MathFuncs::MyMathFuncs::Divide(a, 0) << endl;
}
catch (const invalid_argument &e)
{
cout << "Caught exception: " << e.what() << endl;
}
}
catch (...){
cout << "Problem when loading dll file" << endl;
}
system("pause");
return 0;
}
PS:
我也试过没有这个LoadLibrary()
功能。
我也尝试过:->在项目中添加了 .lib、.h、.dll 文件;
->在控制台应用程序文件夹的同一文件夹中添加了.lib、.h、.dll文件;
->在项目的引用中添加了.lib、.h、.dll文件(C++共享选项)。
我的想法:编译器正在读取 MathFuncsDLL.h,一旦它在我编写主程序的代码时找到函数/类。
到目前为止我遇到的问题:
[ilink32 错误] 错误:从 C:\USERS\MAURO\DESKTOP\PROJETO\WIN32\DEBUG\FILE1.OBJ 引用的无法解析的外部 'MathFuncs::MyMathFuncs::Add(double, double)'
[ilink32 错误] 错误:从 C:\USERS\MAURO\DESKTOP\PROJETO\WIN32\DEBUG\FILE1.OBJ 引用的无法解析的外部 'MathFuncs::MyMathFuncs::Subtract(double, double)'
[ilink32 错误] 错误:从 C:\USERS\MAURO\DESKTOP\PROJETO\WIN32\DEBUG\FILE1.OBJ 引用的无法解析的外部 'MathFuncs::MyMathFuncs::Multiply(double, double)'
[ilink32 错误] 错误:从 C:\USERS\MAURO\DESKTOP\PROJETO\WIN32\DEBUG\FILE1.OBJ 引用的无法解析的外部 'MathFuncs::MyMathFuncs::Divide(double, double)'
编译器的详细信息:-> C++ builder XE7。
从现在开始,非常感谢。