Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare and define global variables in order to access them from all headers/source files properly

Tags:

Well, I'm learning C++ and never really learned how to do stuff that is not OO. I'm trying to get a bit more experience coding in C style.

GobalInformation.h

#pragma once

#ifndef GLOBALINFORMATION_H
#define GLOBALINFORMATION_H

#include "MapInformation.h"

namespace gi {
    MapInformation mapInf;
};

#endif

I would like to be able to access gi::mapInf from every header and cpp in my project. Right now I'm including globalinformation.h in every header, so I'm getting linker errors with multiple definitions.

How can I work around the problem?

like image 851
xcrypt Avatar asked Nov 29 '11 20:11

xcrypt


People also ask

How do you declare a global variable in a header file?

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.

How do you declare a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

Can you define variables in header file?

Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.

How do you declare a global variable in C++?

To declare global variables in C++, we can declare variables after starting the program. Not inside any function or block. If we want to declare some variables that will be stored in some different file, then we can create one file, and store some variable.


1 Answers

In header file only do

namespace gi {
    extern MapInformation mapInf;
};

In CPP file provide the actual definition.

namespace gi {
    MapInformation mapInf;
};

It will work as you intend.

If you are using the MapInformation across dynamic link library boundaries you might have to link against the library that includes the definition cpp file. Also on Window you might have to use dllimport/dllexport

like image 135
parapura rajkumar Avatar answered Oct 02 '22 21:10

parapura rajkumar