【发布时间】:2022-01-05 05:39:30
【问题描述】:
我有里面有 2 个项目的解决方案。在作为库构建的第一个项目中,我有模板类
啊.h
#pragma once
#include <memory>
template<class MessageType, class HandlerType>
class A
{
std::unique_ptr<MessageType> msg;
std::unique_ptr<HandlerType> handler;
public:
A() : msg(std::make_unique<MessageType>()), handler(std::make_unique<HandlerType>()) {}
virtual ~A() {}
};
然后派生类
b.h
#include "a.h"
#include <string>
struct MyMessage
{};
struct MyHandler
{};
class B : A<MyMessage, MyHandler>
{
std::string name;
public:
B(const std::string& str);
virtual ~B();
};
并实施它
b.cpp
#include "b.h"
B::B(const std::string& str)
{
}
B::~B()
{}
此代码构建为静态库 (.lib)。但是当我尝试在主项目中使用 B 类的实例时:
process.cpp
#include <iostream>
#include "b.h"
int main()
{
std::cout << "Hello World!\n";
B opa("yes");
}
编译器无法链接
Rebuild started...
1>------ Rebuild All started: Project: ConsoleApplication3, Configuration: Debug Win32 ------
1>b.cpp
1>ConsoleApplication3.cpp
1>Generating Code...
1>ConsoleApplication3.vcxproj -> C:\Users\user\source\repos\tmpClass\Debug\ConsoleApplication3.lib
2>------ Rebuild All started: Project: tmpClass, Configuration: Debug Win32 ------
2>process.cpp
2>process.obj : error LNK2019: unresolved external symbol "public: __thiscall B::B(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0B@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main
2>process.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall B::~B(void)" (??1B@@UAE@XZ) referenced in function _main
2>C:\Users\user\source\repos\tmpClass\Debug\tmpClass.exe : fatal error LNK1120: 2 unresolved externals
2>Done building project "tmpClass.vcxproj" -- FAILED.
========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ==========
【问题讨论】:
-
看来这里的问题只是关于如何编译多个文件;模板与问题无关。显然有一个名为
process.cpp的文件被编译为生成process.obj,并且在您显示的输出中没有提到b.cpp或b.obj。您之前是否成功编写过涉及多个源文件的项目? (注意:不要在任何地方#include "b.cpp";这不是正确的解决方案) -
我只是展示示例,因为我无法附加整个项目。但是,如果我在没有 b.cpp 的头类中实现 B 类,那么一切都可以。
-
您尚未将
b.cpp添加到您的项目中。它没有被编译,或者至少没有链接。 -
您需要提供更多详细信息。您的项目包含(至少)两个源文件,
process.cpp和b.cpp。错误消息看起来像是在说只有其中一个被链接。如果是这样,那么问题出在项目的设置上,而不是代码上。 -
它存在并编译。 a.h、b.h 和 b.cpp 存在于解决方案中的单独项目中并编译为库。但在 process.cpp 我使用那个 B 类。
标签: c++ visual-studio class templates linker-errors