简体   繁体   English

链接自己的静态库时无法解析的外部符号

[英]Unresolved external symbol when linking my own static library

When I'm trying to link my own library to my project these errors appear: 当我尝试将自己的库链接到我的项目时,出现以下错误:

.\main.cpp(10) : warning C4091: 'extern ' : ignored on left of 'Hamster' when no variable is declared

main.obj : error LNK2001: unresolved external symbol "public: void __thiscall Hamster::SetHealth(int)" (?SetHealth@Hamster@@QAEXH@Z)

I completely don't know what to do. 我完全不知道该怎么办。 I have been searching for the solution on the net but without result. 我一直在网上寻找解决方案,但没有结果。

(Compiled using Visual Studio C++, MS Windows XP) (使用Visual Studio C ++,MS Windows XP编译)

Source of the static library: 静态库的来源:

struct Hamster
{
public:
    int Health;

    void SetHealth(int newHealth)
    {
        if(newHealth <= 100 && newHealth > 0)
        this->Health = newHealth;
    }
};

Source of the console program 控制台程序的源

#include <iostream>
using namespace std;

#pragma comment(lib, "../Release/mylib.lib")

extern struct Hamster
{
public:
    int Health;
    void SetHealth(int newHealth);
};

void main()
{
    Hamster White;
    White.SetHealth(100);

    cout << White.Health << endl;
}

Could you take a look and explain what is wrong? 您能看一下并解释出什么问题吗? Thanks in advance. 提前致谢。

您可能希望将函数声明移出struct ,以使其不是“内联”函数。

You're defining Hamster in both cpp files, but differently; 您在两个cpp文件中都定义了仓鼠,但是方式有所不同。 that's not allowed. 那是不允许的。 (The "One Definition Rule" says so.) (“一个定义规则”就是这样。)

What you need to do is move the definition of struct Hamster into a header file, and include that header file in main.cpp and in your other .cpp file 您需要做的是将struct Hamster的定义移到头文件中,并将该头文件包含在main.cpp和其他.cpp文件中。

(If you leave the definition of SetHealth where it is, you don't actually need the other .cpp file - or indeed the static library. By defining the function in the class you make it inline. For more complex functions it is normal to omit the definition of the function from the class definition and instead include it in exactly one .cpp file.) (如果将SetHealth的定义保留在原来的位置,则实际上不需要其他.cpp文件-甚至不需要静态库。通过在类中定义函数,可以使其内联。对于更复杂的函数,通常从类定义中忽略函数的定义,而只将其包含在一个.cpp文件中。)

If you really want to get a library and an executable that uses your library you have to make two projects in visual studio. 如果您确实想要获得一个库和使用该库的可执行文件,则必须在Visual Studio中创建两个项目。

The first one builds the static library and the second builds your executable. 第一个构建静态库,第二个构建您的可执行文件。 The project which builds the executable must have a dependancy on the library. 生成可执行文件的项目必须依赖于库。

Moreover declare your structure in a header file and includes it your main.cpp 此外,在头文件中声明您的结构并将其包含在您的main.cpp中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM