简体   繁体   中英

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)

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; 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

(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.)

If you really want to get a library and an executable that uses your library you have to make two projects in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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