c++ - 使用没有内联代码的 dll 时出现 LNK2028 和 LNK2019 错误

标签 c++ .net dllimport unmanaged lnk2019

这是我第一次使用 .NET,它让我在使用多个项目时遇到困难。我究竟做错了什么?这就是我所做的:

1 创建一个新项目(和解决方案)。名为“Lib”的“类库”。

2 使用以下代码将文件“Comp1.h”添加到“头文件”:

#ifndef COMP1_H
#define COMP1_H
class comp1
{
public:
    comp1(void);
    ~comp1(void);
}
#endif

3 使用以下代码将文件“Comp1.cpp”添加到“源文件”:

#include "stdafx.h"
#include "Comp1.h"
comp1::comp1(void){}
comp1::~comp1(void){}

4 我用以下内容覆盖自动创建的“Lib.h”文件的代码:

#ifndef LIB_H
#define LIB_H
#include "Comp1.h"
#endif

5 添加一个名为“Test”的“CLR empty project”并将其设置为启动项目。

6 使用以下代码将文件“test.cpp”添加到“测试”项目的“源文件”:

#include "../Lib/Lib.h"
#using "../Debug/Lib.dll"//Is this line mandatory?
int main()
{
comp1 component;
return 0;
}

7 在“Test”属性中添加“Lib”作为引用。

8 确保在“Project Dependencies”中“Test”依赖于“Lib”。

9 将它们都编译为/clr

这是我得到的:

1>test.obj : error LNK2028: unresolved token (0A000009) "public: __thiscall comp1::comp1(void)" (??0comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
1>test.obj : error LNK2028: unresolved token (0A00000A) "public: __thiscall comp1::~comp1(void)" (??1comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
1>test.obj : error LNK2019: unresolved external symbol "public: __thiscall comp1::~comp1(void)" (??1comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
1>test.obj : error LNK2019: unresolved external symbol "public: __thiscall comp1::comp1(void)" (??0comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)

如果我创建内联函数,则不会出现此问题。

在论坛上,您可以找到有关包含文件错误的答案,但我很确定我编写的所有代码都是正确的。

谢谢。

最佳答案

当您创建 DLL 时,您必须使用 __declspec(dllexport) 指令明确标记要导出的函数和类,从而使它们可供客户端导入。当您导入类时,您必须使用 __declspec(dllimport) 指令。

This document展示了如何在 header 中标记类和全局函数,以便它们可用于导出和导入。

关于c++ - 使用没有内联代码的 dll 时出现 LNK2028 和 LNK2019 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14216119/

相关文章:

c++ - 未解析的外部符号 _declspec(dllimport)

C++ 多线程调试宏

c# - 通过 XAML 可用的 WPF 的哪些功能不能通过 C#(或 VB,...)

c# - 从 C++ 到 C# 的二进制/十六进制数据的编码/DllImport

c# - 在 C# 中将 WriteableBitmap 转换为位图

c# - SignedXml 报告 "Unknown transform has been encountered."

c++ - 手动填写DLL导入表 : IMAGE_IMPORT_DESCRIPTOR's Name field stores 0x0000FFFF

c++ - 为什么我的图书馆管理程序没有写入文件

c++ - 使用写函数传递 int 表

c++ - 使用类指针拆分项目