繁体   English   中英

Visual Studio 的 LNK2019 错误 - 无法解析的外部符号

[英]LNK2019 error for Visual Studio - unresolved external symbol

我是初学者,遇到了上述错误。 以下是来自三个文件的完整代码: ball.h

#ifndef BALL_H
#define BALL_H
namespace
{
    inline constexpr double gravity{ 9.81 };
}
    double getInitialHeight(void);
    double calculateHeight(double, int);
    void printHeight(double, int);
    void calculateAndPrintHeight(double, int);
    void solve(void);

#endif

ball.cpp :

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

double getInitialHeight()
{
    std::cout << "Enter the height of the tower in meters ";
    double initialHeight{};
    std::cin >> initialHeight;
    return initialHeight;
}

double calculateHeight(double initialHeight, int secondsPassed)
{
    double distanceFallen{ BALL_H::gravity * secondsPassed * secondsPassed / 2.0 };
    double currentHeight{ initialHeight - distanceFallen };
    return currentHeight;
}

void printHeight(double height, int secondsPassed)
{
    if (height > 0.0)
    {
        std::cout << "At " << secondsPassed << " seconds, the ball is at height\t" << height << " meters.\n";
    }
    else
    {
        std::cout << "At " << secondsPassed << " seconds, the ball is on the ground.\n";
        std::exit(0);
    }


}

void calculateAndPrintHeight(double initialHeight, int secondsPassed)
{
    double height{ calculateHeight(initialHeight, secondsPassed) };
    printHeight(height, secondsPassed);
}

void solve()
{
    const double initialHeight{ getInitialHeight() };
    int secondsPassed{ 0 };
    while (true)
    {
        calculateAndPrintHeight(initialHeight, secondsPassed);
        secondsPassed++;
    }
}

Solution.cppSolution.cpp的主项目文件):

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

int main()
{
    solve();
    return 0;
}

我知道这个问题是因为链接器找不到对solve()的引用造成的。 但是,我不确定如何解决这个问题。 一种简单的解决方案是简单地包含ball.cpp而不是ball.h

#include <iostream>
#include "ball.cpp"

int main()
{
    solve();
    return 0;
}

这段代码有效,但我想知道如何改用标头,因为我不确定这是否是一个好习惯。

编辑:这是错误列表:

在此处输入图片说明

添加头文件时,您可以右键单击Header Files并选择Add->New Item

在此处输入图片说明

添加 .cpp 文件时,您可以右键单击Source Files并选择Add->New Item

在此处输入图片说明

然后,在Source.cpp添加以下代码。

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

int main()
{
    solve();
    return 0;
}

最后,它工作正常。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM