C++ include guard 似乎不起作用?

标签 c++ file header include guard

我以前曾多次使用过 include guards,但从未真正理解它们的工作原理和原因。

为什么以下不起作用?

#ifndef CAMERA_CLASS_HPP
#define CAMERA_CLASS_HPP


class camera_class
{
....
};

camera_class glcam = camera_class();


#endif // CAMERA_CLASS_HPP

错误是这样的:(你大概可以从这个问题的标题中猜到它会是什么!)

-------------- Build: Debug in System ---------------

Linking console executable: bin/Debug/System
/usr/bin/ld: error: obj/Debug/main.o: multiple definition of 'glcam'
/usr/bin/ld: obj/Debug/camera_class.o: previous definition here
/usr/bin/ld: error: obj/Debug/main.glfunc.o: multiple definition of 'glcam'
/usr/bin/ld: obj/Debug/camera_class.o: previous definition here
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings

此外,有人可以向我解释一下为什么头球后​​卫会起作用吗?

最佳答案

header guard 将防止在单个翻译单元中包含多个内容。 header 可以(并且正在)包含在多个翻译单元中:

// a.cpp:
#include "camera.hpp"

// b.cpp
#include "camera.hpp"

这将生成一个 a.obj 和一个 b.obj,每个都包含一个 glcam 的定义。当链接在一起生成最终的二进制文件时,您会遇到多重定义错误。

您需要在 header 中声明 glcam 并在 .cpp 文件中定义它一次:

// camera.hpp
...

extern camera_class glcam;

// camera.cpp
#include "camera.hpp"

camera_class glcam;

关于C++ include guard 似乎不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12320387/

相关文章:

java - 从jar中读取资源文件

node.js - 为什么将 View 包含在 .ejs 文件中时无法识别?

c++ - 用于创建新作用域的最佳 C++ 宏

c++ - 如何禁用特定文件的 Visual C++ 内存泄漏检查?

java - Android 多文件上传到服务器

wpf - 获取 WPF 扩展器标题的高度

php - 如何读取用PHP上传的文件的标题?

android - AAudio 或 OpenSL

c++ - 如果共享内存的指针为空,则将其内容设置为空 c++

git - 使用 git-annex 管理许多小(~5KB)文件