编译器抱怨即使有警卫在场也重新定义

Compiler complains about redefinition even with guards present

本文关键字:新定义 定义 在场 有警 编译器      更新时间:2023-10-16

我正在尝试为OpenGL应用程序设置一些日志记录函数。GLFW 提供了注册回调函数的选项,每当发生错误时都会调用该函数,但由于它是一个 C 库,因此它要求该函数以 C 样式编写,即在类之外。因此,我将日志记录函数放入文件log.h中定义的命名空间中。

#ifndef LOG_H
#define LOG_H
#include <fstream>
namespace gllog{    
  #define GL_LOG_FILE "gl.log"
  bool restart_gl_log(){
    //...
  }
  bool gl_log (const char* message, const char* filename, int line){
    //...
  }
  void glfw_error_callback (int error, const char* description){
    //...
  }  
};
#endif

即使我添加了包含保护,每当我从两个不同的文件包含此文件时,我也会收到如下错误:

CMakeFiles/gl4tuts.dir/extended_initialisation/ExtendedInitialisation.cpp.o: In function `gllog::glfw_error_callback(int, char const*)':
ExtendedInitialisation.cpp:(.text+0x340): multiple definition of `gllog::glfw_error_callback(int, char const*)'
CMakeFiles/gl4tuts.dir/hello_triangle/HelloTriangle.cpp.o:HelloTriangle.cpp:(.text+0xa10): first defined here

我正在使用CMake构建。

可能是什么原因?没有类可能有关吗?

包含保护可防止您在编译同一.cpp文件时多次包含相同的头文件。它们不会阻止您在编译不同的.cpp文件时多次包含相同的头文件 - 实际上,它们通常用于使同一类在不同的编译单元中可用。

顺便说一下,编译器没有抱怨,链接器是。