简体   繁体   中英

Creating class object defined in another project

I have a Visual C++ solution with 2 projects: rectangle and project3 .

In rectangle project I have rect.cpp and rect.h .

rect.h

#ifndef rect_h
#define rect_h
class Rect
{
public:
    Rect();

    int m_h;
    int m_w;
};
#endif //rect_h

rect.cpp

#include "rect.h"
Rect::Rect()
{
    m_h = 1;
    m_w = 5;
}

whenever I try to create rect object from the rectangle project it succeeds.

But when I try to do the same from the project3 it produces a linker error.

LNK2019: unresolved external symbol "public: __thiscall Rect::Rect(void)" (??0Rect@@QAE@XZ) referenced in function _main 1>C:\\Users\\mbaro\\documents\\visual studio 2017\\Projects\\Project2\\Debug\\Project3.exe : fatal error LNK1120: 1 unresolved externals

main.cpp (in project 3)

#include "rect.h"
using namespace std;

int main()
{
    Rect* a = new Rect();

    return 0;
}

I kind of feel that class definition is picked up successfully, but the linker can not link the constructor code from rect.cpp.

What is the problem and how to solve it?

Thanks.

The error is normal: you told the compiler where it could find the .h files, but you did not tell the linker where it could find the .obj files.

It may depend on the exact VS version, but in Project/Properties, you should find Linker/Input and there Additional dependencies. If you only need one or two object files ( xxx.obj ) from the other project, add them here. That way, you avoid code duplication, which will be a nightmare for future maintenance...

If you have many common files, you should considere to put them in an auxilliary project that would build a (static)library in the same solution, and then link the library in both project (and of course give access to header files of the library project for the other projects using the library).

I have already started writing a long, long answer. Then i realized, what You may be missing is that despite Your class is named "Person" the header file You should have added is named "rect.h".

Also Your constructor cannot have a declaration of values in the header file (EDIT:not true, I was mistaken). In the header file, try using:

Person(int h, int w);

You declare what will be needed, not what You already have. If You want those to be specifically what You wrote the constructor should be:

Person();

in .h

and

Person::Person()
{
m_h = 1;
m_w = 5;
}

in .cpp.

If You need more detailed description of using include, I have already written a big part of it, so don't hesitate to ask.

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