更新 2:发现导致此问题的前向声明错误
更新:使用 Visual Studio 2010 标准编译器进行编译,启用 c++0x。
我有一个带有成员函数的类,该函数的行为很奇怪。
当我在 cpp 文件中定义方法时,链接器因“无法解析的外部符号”错误而崩溃。当我将定义移至 header 时,它可以正常编译。
1) 这不是模板化方法 2)cpp文件肯定正在编译 3)我被难住了
有什么想法吗?
头文件
// THIS IS THE ERROR HERE: I forward declare TPA as a class, when it is actually a struct
class TollingPathAttributes; // forward declare the TollingPathAttributes struct as a class (doh!)
class TollingPathAttributesOutput
{
public:
TollingPathAttributesOutput(HighwayCommand* command);
~TollingPathAttributesOutput();
void foo();
void AddPathAttributes(boost::shared_ptr<TollingPathAttributes> attributes);
protected:
string m_outputFilename;
vector<shared_ptr<TollingPathAttributes>> m_data;
queuing_mutex m_dataMutex;
};
cpp文件
void TollingPathAttributesOutput::foo() {}
void TollingPathAttributesOutput::AddPathAttributes(boost::shared_ptr<TollingPathAttributes> attributes)
{
queuing_mutex::scoped_lock lock(m_dataMutex);
m_data.push_back(attributes);
}
调用调用
m_output->foo(); // compiles and links no problem
boost::shared_ptr<TollingPathAttributes> attr =
boost::make_shared<TollingPathAttributes>(origin, dest, UNTOLLED_OPTION, vector<int>(), 0.0, 0.0);
m_output->AddPathAttributes(attr); // compiles fine, but only links correctly if I move the definition to the header
链接错误
1>OtCustomZenith_logic.lib(TollingPathAttributesRecorder.obj) : error LNK2019: unresolved external symbol "public: void __thiscall TollingPathAttributesOutput::AddPathAttributes(class boost::shared_ptr<class TollingPathAttributes>)" (?AddPathAttributes@TollingPathAttributesOutput@@QAEXV?$shared_ptr@VTollingPathAttributes@@@boost@@@Z) referenced in function "public: virtual void __thiscall TollingPathAttributesRecorder::Record(class TolledPath &,class boost::shared_ptr<class Path>,int)" (?Record@TollingPathAttributesRecorder@@UAEXAAVTolledPath@@V?$shared_ptr@VPath@@@boost@@H@Z)
1>..\..\..\OT\OtCustomZenith_test.exe : fatal error LNK1120: 1 unresolved externals
最佳答案
感谢每一位试图提供帮助的人 - 不幸的是,这个错误距离键盘大约 1 英尺。这里的问题归结为使用前向声明来加快编译时间。因为我错误地将 TollingPathAttributes 的类型声明为类而不是结构。
这意味着 header 的定义与 cpp 中的定义略有不同,因为我实际上在 cpp 文件中包含了 TollingPathAttributes 的完整定义。使这个问题困惑的最重要的事情是我收到的错误消息不是我期望收到的 - 正如@MarkRansom所说,通常如果cpp和 header 之间不匹配,它将是一个编译错误而不是链接错误,所以我必须得出这样的结论:
1) 编译器只是简单地推进了基于错误的“类”(而不是“结构”)的定义,即使它在拥有可用的完整定义后就知道得更好。生成一个 lib 文件,该文件的签名几乎但不完全是链接器正在寻找的签名。
2)其他一些奇怪的事情
关于c++ - 当方法在 cpp 文件中定义时未解析外部,但在 header 中则未解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10115912/