开发者

C++: Constructor/destructor unresolved when not inline?

In a plugin-based C++ project, I have a TmpClass that is used to exchange data b开发者_Go百科etween the main application and the plugins. Therefore the respective TmpClass.h is included in the abstract plugin interface class that is included by the main application project, and implemented by each plugin.

As the plugins work on STL vectors of TmpClass instances, there needs to be a default constructor and destructor for the TmpClass. I had declared these in TmpClass.h:

class TmpClass {
  TmpClass();
  ~TmpClass();
}

and implemented them in TmpClass.cpp.

TmpClass::~TmpClass() {}
TmpClass::TmpClass() {}

However, when compiling plugins this leads to the linker complaining about two unresolved externals - the default constructor and destructor of TmpClass as required by the std::vector<TmpClass> template instantiation - even though all other functions I declare in TmpClass.h and implement in TmpClass.cpp work. As soon as I remove the (empty) default constructor and destructor from the .cpp file and inline them into the class declaration in the .h file, the plugins compile and work.

Why is it that the default constructor and destructor have to be inline for this code to compile? Why does it even maatter? (I'm using MSVC++8).


The behavior you describe simply means that you forgot to include the TmpClass.cpp file into the project.

The compiler cannot and will not magically know where the non-inline class methods are defined. It is your responsibility to compile all .cpp files and link them together. In MSVC it is normally done by adding all .cpp files to the project.


I'm guessing you have one "main application" project and one or more "plugin" projects and it looks like you haven't included TmpClass.cpp in the plugins project. I'm also guessing "all other function you declare in the .h and implement in .cpp" are only used by your main project and not by your plugins.

As others have said, you can include TmpClass.cpp across your plugin projects. The other option is to create a dll "sdk" project and link both the main and plugins project against it.

If you still think this and AndreyT's answers are wrong, you should provide some more information about your projects structure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜