【问题标题】:Why am I getting a linker error even though both files are in the same directory?为什么即使两个文件都在同一个目录中,我也会收到链接器错误?
【发布时间】:2017-10-26 21:55:08
【问题描述】:

我正在从事一个涉及三维空间中的数学向量的项目(不要与vector 集合类型混淆)。我在Vector.cpp 中定义了一个class Vector,并在Vector.h 中声明。我的目录结构如下:

当我尝试构建项目时,我收到 LNK2019 未解决的外部符号错误。据我所知,我的所有三个文件都在构建路径上。

Vector.cpp:

class Vector
{
private:
    double xComponent;
    double yComponent;
    double zComponent;
public:
    Vector(double x, double y, double z) : xComponent(x), yComponent(y), zComponent(z) {}

    double dotProduct(const Vector& other) const
    {
        return xComponent * other.xComponent + yComponent * other.yComponent + zComponent * other.zComponent;
    }
}

Vector.h:

#ifndef VECTOR_H
#define VECTOR_H
class Vector
{
public:
    Vector(double x, double y, double z);
    double dotProduct(const Vector& other) const;
}
#endif

Vectors.cpp:

#include "Vector.h"
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    Vector foo = Vector(3, 4, -7);
    Vector bar = Vector(1.2, -3.6, 11);
    cout << foo.dotProduct(bar) << endl;
    return 0;
}

foo.dotProduct(bar) 是唯一发生链接器错误的地方(构造函数上没有发生错误)。我尝试了Vector 的其他一些非构造方法,它们也导致了链接器错误。为什么构造函数可以工作,而其他任何一个都不能工作?

这是尝试构建项目的输出:

1>------ Build started: Project: Vectors, Configuration: Debug Win32 ------
1>Vectors.obj : error LNK2019: unresolved external symbol "public: double __thiscall Vector::dotProduct(class Vector const &)const " (?dotProduct@Vector@@QBENABV1@@Z) referenced in function _main
1>C:\Users\John\Documents\Visual Studio 2017\Projects\Vectors\Debug\Vectors.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "Vectors.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

【问题讨论】:

  • 向量应该在一个文件中声明,而不是两个。
  • @NeilButterworth 我不太确定我明白你的意思。我不需要在头文件中前向声明它以便可以在Vectors.cpp中使用吗?
  • nope - vector.cpp 应该只有方法体。还请包括实际的错误文本
  • 没有。您已经在 .h 和 .cpp 文件中声明了它。请参考 C++ 教科书。
  • 并且没有正确包含方法体 - 因此链接错误

标签: c++ visual-studio linker visual-studio-2017


【解决方案1】:

你定义了两次类。一次在标头中,一次在 .cpp 文件中。

在 .cpp 文件中只保留函数定义:

#include "Vector.h"

Vector::Vector(double x, double y, double z) : xComponent(x), yComponent(y), zComponent(z) 
{
}

double Vector::dotProduct(const Vector& other) const
{
    return xComponent * other.xComponent + yComponent * other.yComponent + zComponent * other.zComponent;
}

每次你写class SomeClass {};,你定义一个符号。命名空间中只能定义一个具有给定名称的符号。

请阅读有关声明和定义的更多信息。你可以start here

【讨论】:

  • 谢谢。我从中学到的 C++ 书假设所有代码都写在一个文件中,因此我很困惑。
猜你喜欢
  • 2020-10-25
  • 2013-08-20
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2018-04-10
  • 2022-06-12
  • 1970-01-01
相关资源
最近更新 更多