“...”的多重定义C [英] Multiple Definition of "..." 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'|
推荐答案
包含防护只能防止单个翻译单元中的多个定义文件及其包含的标题)。当您包括多个源文件的标题时,它们不会阻止多个定义。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!