c++ - 如何在 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"
| ^~~~~~~
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;
}
有人知道使用头文件运行此代码而不会出现任何错误吗?
解决方案
这个问题的一个非常简单的解决方案是执行以下命令:
g++ -o main main.cpp npc.cpp && ./main
这将告诉编译器将npc.cpp
文件与主可执行文件链接。当我没有包含npc.cpp
在命令行中时,该错误在我的机器中会产生:
g++ -o main main.cpp && ./main
这引发了关于未定义的对类成员函数的引用的错误,这些类成员函数在npc.cpp
.
推荐阅读
- google-compute-engine - 如何抢救实例启动盘?
- schema.org - 面包屑中的错误:“项目字段的值是必需的”
- python - ColumnDataSource 上的散景流未更新绘图
- npm - 在 HTTP 重定向的情况下如何捕获最终响应
- performance - JMeter 需要 3 分钟打开 3mb jmx 脚本文件
- python - python sklearn中的'ValueError:无法将字符串转换为浮点数'
- php - 关于 Twitter 的 PHP API 海报的建议
- encoding - 为什么在 asp.net 类 (vb) 中使用 FTPUpload 发布错误的字符?
- azure - 使用 PowerShell 列出 blob、文件、表、队列的已用空间?
- reactjs - 如何使用 axios 更改 json 数据中的单个值