提问者:小点点

如何在vs代码中链接。h文件?


我是C++的新手,我有三个文件main.cpp,npc.cpp和npc.h。 我尝试运行它,出现以下错误:

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

编译终止。

下面是我的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;
}

有人知道在没有任何错误的情况下用头文件运行这段代码吗?


共1个答案

匿名用户

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

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

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

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

这引发了一个关于未定义的类成员函数引用的错误,这些函数是在npc.cp中定义的。