gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:38:01 26 4
gpt4 key购买 nike

我以前曾多次使用过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com