c++ - 使用头文件中的类声明时出现链接器错误
问题描述
我正在一个名为“initialize.cpp”的文件中设置一个类,并在“Engine.h”中添加一个声明。当我尝试在 Main 中使用该类时,它会给我正在使用的每个函数的链接器错误。
unresolved external symbol "public: int __cdecl Application::run(void)" (?run@Application@@QEAAHXZ) referenced in function main
unresolved external symbol "public: int __cdecl Application::loop(void)" (?loop@Application@@QEAAHXZ) referenced in function main
unresolved external symbol "public: int __cdecl Application::termination(void)" (?termination@Application@@QEAAHXZ) referenced in function main
这是初始化.cpp
#include<GL/glew.h>
#include <GLFW/glfw3.h>
class Application {
public:
int run() {
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(1600, 900, "OpenGL Window", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
return 0;
}
void loop() {
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
}
int termination() {
glfwTerminate();
return 0;
}
private:
GLFWwindow* window;
};
这是头文件
#pragma once
class Application {
public:
int run();
int loop();
int termination();
private:
};
和主要
#include "Engine/Engine.h"
int main()
{
Application application;
application.run();
application.loop();
application.termination();
return 0;
}
请记住,我对 C++ 还很陌生,如果我忽略了一些愚蠢的事情,我很抱歉,但让我们学习的总是愚蠢的错误。
解决方案
这是初始化.cpp
#include<GL/glew.h> #include <GLFW/glfw3.h> class Application { public: int run() { /* Initialize the library */ if (!glfwInit()) return -1; //...
这不是您实现类的成员函数的方式。这样做是定义一个完全不同class Application
的,它的所有成员函数都内联并且其他.cpp
文件无法访问,而main.cpp
只看到class Application
在头文件中声明的,其成员函数在任何地方都没有实现。
假设class Application
在 header 中声明initialize.h
,改为initialize.cpp
如下更改。
#include<GL/glew.h>
#include <GLFW/glfw3.h>
#include "initialize.h"
int Application::run() {
/* Initialize the library */
if (!glfwInit())
return -1;
//...
return 0;
}
void Application::loop() {
//...
}
int Application::termination() {
//...
}
推荐阅读
- java - 将jOOQ的批处理加载器与onDuplicateKeyUpdate一起使用时,如何仅更新某些字段?
- security - opencti 虚拟机凭据
- python - 在python中将日期(月、日、年、时间)转换为日期时间格式
- spring - 为什么@RestController 默认使用单例范围?
- powershell - 如何使用 Powershell 脚本在远程计算机上查找 PST 文件
- php - 数据表页面就像只有一页一样工作
- angular - 单击铅笔图标编辑内容
- javascript - JavaScript 对象语法和符号
- json - 从 Bigquery 中的 json 获取数组
- javascript - React Native 和 Apollo 客户端