未解析的外部符号,但函数已定义并实现

Unresolved external symbol but the function is defined and implemented

提问人:beriff 提问时间:11/1/2021 更新时间:11/1/2021 访问量:1306

问:

我有一个头文件,定义了类:chunk

#pragma once
#include <vector>

#include "Tile.h"
#include "Numerics.h"
namespace boch {
    class chunk {
    public:
        chunk();
        static const uint defsize_x = 16;
        static const uint defsize_y = 16;
        std::vector<std::vector<tile*>> tilespace;

        

        tile* getat(vint coords);
        void fillc(tile t);
    };
}

然后,我在文件中定义了类的实现:Chunk.cpp

#include "Chunk.h"

boch::chunk::chunk() {
    tilespace = std::vector<std::vector<tile*>>(defsize_x);
    for (int x = 0; x < defsize_x; x++) {
        std::vector<tile*> temp = std::vector<tile*>(defsize_y);
        tilespace[x] = temp;
    }
}

void boch::chunk::fillc(tile t) {
    for (int x = 0; x < defsize_x; x++) {
        for (int y = 0; y < defsize_y; y++) {
            tilespace[x][y] = new tile(t);
        }
    }
}

boch::tile* boch::chunk::getat(vint coords) {
    return tilespace[coords.x][coords.y];
}

(vint是一个 typedef,其是自定义 X,Y 向量,如果有帮助的话)boch::vector<int>

然后,我在文件的 main 函数中使用它:BochGrounds.cpp

#include <iostream>
#include "Layer.h"
#include "Gamegrid.h"

int main()
{
    boch::layer newlayer = boch::layer(boch::vuint(16, 16));
    boch::chunk newchunk = boch::chunk();
    boch::gamegrid newgrid = boch::gamegrid();

    newchunk.fillc(boch::tile());
    newgrid.addchunk(boch::cv_zero, &newchunk);
    newgrid.drawtolayer(&newlayer);
    newlayer.draw(std::cout);
}

Tile 类定义了 gamegrid 类,chunk 包括 tile 类,gamegrid 包括 chunk & entity(也包括 tile)。图层类仅包含切片。所有头文件都有指令。尝试编译时,出现以下错误:#pragma once

LNK2019 unresolved external symbol "public: __cdecl boch::chunk::chunk(void)" (??0chunk@boch@@QEAA@XZ) referenced in function main

LNK2019 unresolved external symbol "public: void __cdecl boch::chunk::fillc(class boch::tile)" (?fillc@chunk@boch@@QEAAXVtile@2@@Z) referenced in function main

结果:

LNK1120 2 unresolved externals

其他 StackOverflow 答案表明链接器无法看到 both 和 chunk 构造函数的实现,但我不明白为什么它甚至是这里的问题。请帮忙。(链接器设置尚未更改,并且是 MVSC 2019 的默认设置)fillc()

C++ 链接器错误未 解决外部

评论

2赞 Piotr Siupa 11/1/2021
您使用什么命令来编译和链接程序?
4赞 fabian 11/1/2021
需要明确的是:您已经添加了这两个文件,并且是同一个 Visual Studio 项目的一部分,并且这两个文件实际上都已生成?Chunk.cppBochGrounds.cpp
0赞 Retired Ninja 11/1/2021
我会再次验证它确实在项目中并且正在编译,而不仅仅是与您的其他文件在同一目录中。最好直接包含您使用的标头,因此您需要在 .这不是导致错误的原因,但它可以防止在其他文件之一不包含它的情况下,将来可能会发生破坏。Chunk.cppBochGrounds.cpp
0赞 beriff 11/1/2021
@fabian是的,这两个文件都在构建中。
0赞 beriff 11/1/2021
@RetiredNinja感谢您的建议!我实际上已经尝试过包含每个头文件,可悲的是它没有帮助。

答:

0赞 beriff 11/1/2021 #1

感谢糖的回答。我删除了标题和.cpp文件并重新添加了它们,它就像一个魅力。我想我已经添加了头文件或.cpp文件,只需直接将新文件添加到头/源文件夹而不是将其添加到项目中(RMB单击项目>添加新项目)。