Anthony Raimondo
Anthony Raimondo

Reputation: 1721

Problems initializing global variables

HEADER FILE

#ifndef H_MODEL_UTIL
#define H_MODEL_UTIL

#include "Mesh.h"

Mesh *kingHigh;

void InitModel();

#endif 

SOURCE FILE

#include "stdafx.h"
#include "ResourceLoader.h"
#include "ModelUtil.h"

void InitModel()
{
    ::kingHigh  = new Mesh();
}

Compiler output:

1>Game.obj : error LNK2005: "class Mesh * kingHigh" (?kingHigh@@3PAVMesh@@A) already defined in Cube.obj

1>ModelUtil.obj : error LNK2005: "class Mesh * kingHigh" (?kingHigh@@3PAVMesh@@A) already defined in Cube.obj

1>C:\Users\Anthony\Desktop\C++ Learning\Extra\Rubiks Chess\Debug\Rubiks Chess.exe : fatal error LNK1169: one or more multiply defined symbols found

I am trying to initialize a global variable but I keep getting this error. Is there a simple solution?

Upvotes: 0

Views: 145

Answers (2)

esonat
esonat

Reputation: 41

You have redefined Mesh in InitModel.kinghigh is global so its already defined.just delete the content of InitModel.and also you can write extern Mesh *kinghigh

Upvotes: 1

alexbuisson
alexbuisson

Reputation: 8469

The error is not in the way you init mesh , it's in your declaration. your header file should declare mesh as external

 extern Mesh *kingHigh;

and declare mesh in your .cpp file

 Mesh *kingHigh;

it must prevent the multiple definition you got !

Upvotes: 5

Related Questions