Multiple Definition of quot;...quot; c(“……的多重定义C)
问题描述
我有一个头文件USpecs.h":
I have a header file "USpecs.h":
#ifndef USPECS_H
#define USPECS_H
#include "Specs.h"
#include <iostream>
#include <vector>
std::vector<Specs*> UcakSpecs;
#endif
我在 main 函数和另一个名为 Ucak 的类中都使用了这个头文件.
I am using this header both in main function and another class named Ucak.
但是当我构建它时会发生以下错误:
But when i build it the following error occurs:
Ucak.cpp|6|`UcakSpecs'的多重定义|
Ucak.cpp|6|multiple definition of `UcakSpecs'|
正如我之前搜索的那样,#ifndef 应该可以,但事实并非如此.
As i searched before, it should be okay with #ifndef but it is not.
推荐答案
包含守卫仅防止在单个翻译单元(即具有包含标头的单个源文件)中出现多个定义.当您包含来自多个源文件的标头时,它们不会阻止多个定义.
The include guards only prevent multiple definitions within a single translation unit (i.e. a single source file with its included headers). They do not prevent multiple definitions when you include the header from multiple source files.
相反,您应该在标题中声明:
Instead, you should have a declaration in the header:
extern std::vector<Specs*> UcakSpecs;
在一个(也是唯一一个)源文件中定义:
and a definition in one (and only one) source file:
std::vector<Specs*> UcakSpecs;
这篇关于“……"的多重定义C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“……"的多重定义C
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01