Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Definition of "..." c

Tags:

c++

header

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

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|multiple definition of `UcakSpecs'|

As i searched before, it should be okay with #ifndef but it is not.

like image 731
mucisk Avatar asked Apr 02 '13 13:04

mucisk


People also ask

What is multiple definition of main in C?

Multiple definition of main means you have written main function more than once in your program which is not correct according to C language specifications.

What is multiple definition error in C?

If you put a definition of a global variable in a header file, then this definition will go to every . c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

What are definitions in C?

In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables.

What does multiple definition of main mean in c++?

Multiple definitions of "main" suggests that you have another definition of main. Perhaps in another . c or . cpp file in your project. You can only have one function with the same name and signature (parameter types).


1 Answers

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;
like image 58
Mike Seymour Avatar answered Oct 27 '22 22:10

Mike Seymour