1

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

You may want to move the function declaration out of the struct, so that it is not an "inline" function.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.