首页 > 解决方案 > 使用头文件中的类声明时出现链接器错误

问题描述

我正在一个名为“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++ 还很陌生,如果我忽略了一些愚蠢的事情,我很抱歉,但让我们学习的总是愚蠢的错误。

标签: c++oop

解决方案


这是初始化.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() {
//...
}

推荐阅读