首页 > 解决方案 > 如何在 vs 代码中链接 .h 文件?

问题描述

我是 C++ 新手,我有三个文件main.cppnpc.cppnpc.h。我尝试运行它并出现此错误:

main.cpp:2:10: fatal error: npc.h: No such file or directory
2 | #include "npc.h" 
  |          ^~~~~~~ 

compilation terminated.

这是我的main.cpp

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

int main(int argc, char const *argv[])
{
    NPC Tom(100, 45);

    Tom.Stats();

    return 0;
}

npc.h

#ifndef NPC_H
#define NPC_H

class NPC
{
public:
    NPC();
    ~NPC();
    NPC(int life, int level);
    void Stats();

private:
    int m_life;
    int m_level;
};

#endif /*NPC_H*/

最后,npc.cpp

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

NPC::NPC()
{
}

NPC::~NPC()
{
}

NPC::NPC(int life, int level) : m_life(life), m_level(level)
{
}

void NPC::Stats()
{
    std::cout << "This npc has " << m_life << " and is at level " << m_level << "." << std::endl;
}

有人知道使用头文件运行此代码而不会出现任何错误吗?

标签: c++visual-studio-code

解决方案


这个问题的一个非常简单的解决方案是执行以下命令:

g++ -o main main.cpp npc.cpp && ./main

这将告诉编译器将npc.cpp文件与主可执行文件链接。当我没有包含npc.cpp在命令行中时,该错误在我的机器中会产生:

g++ -o main main.cpp && ./main

这引发了关于未定义的对类成员函数的引用的错误,这些类成员函数npc.cpp.


推荐阅读