How to Declare and Define Global Variables in Order to Access Them from All Headers/Source Files Properly

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

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

Global variables in header file

There are 3 scenarios, you describe:

  1. with 2 .c files and with int i; in the header.
  2. With 2 .c files and with int i=100; in the header (or any other value; that doesn't matter).
  3. With 1 .c file and with int i=100; in the header.

In each scenario, imagine the contents of the header file inserted into the .c file and this .c file compiled into a .o file and then these linked together.

Then following happens:

  1. works fine because of the already mentioned "tentative definitions": every .o file contains one of them, so the linker says "ok".

  2. doesn't work, because both .o files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o files which are linked together at a given time.

  3. works of course, because you have only one .o file and so no possibility for collision.

IMHO a clean thing would be

  • to put either extern int i; or just int i; into the header file,
  • and then to put the "real" definition of i (namely int i = 100;) into file1.c. In this case, this initialization gets used at the start of the program and the corresponding line in main() can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i in real programs.)

Where can I declare global variable in c program , whether in header or source file

Assuming your variable is global and non static.

You need to declare it in a header file. We use extern keyword for this. As pointed out in comments, this keywords is not necessary, but most C users prefer to use it in headers, this is a convention.

stackoverflow.h:

#ifndef STACHOVERFLOW_H
#define STACHOVERFLOW_H

extern int my_var;

#ifndef

And you initialize it in source file. (Use of keyword extern is prohibited if you want to provide an initialization value).

stackoverflow.c

#include "stackoverflow.h"

int my_var = 50;

Do not put initialization value in a header, or you will get a linker error if the header is used at least twice.

Now you can use your variable in any other module by including the header.

main.c

#include <stdio.h>
#include "stackoverflow.h"

int main()
{
printf("my_var = %d\n", my_var);
return 0;
}

Including header "stackoverflow.h" in "stackoverflow.c" is a way to get sure definitions in source file match declarations in header file. This permit to have errors as soon as compilation instead of sometimes cryptic linker errors.

Edit: This is not at all the way to make a variable "private". You have to use a static variable to make it "private". See R Sahu's answer

Issue with Headers and Global Variable

In source.cpp you need to define the variable:

int variable = 17;

Read variable from C++ header in Objective-c

You can have problems with multiple definitions when defining a variable in a header file (how to declare and define global variables in order to access them from all headers/source files properly).

Can you stop including the header file and instead add a line such as:

extern CPPEng *a;

Multiple definition error on variable that is declared and defined in header file and used only in its cpp file

If you declare your variable in the header file:

#ifndef GLOBAL_H
#define GLOBAL_H

int foo = 0;

#endif

In every include of your header file or translation unit, a new instance of your integer is created. As you mentioned, to avoid this, you need to declare the item as "extern" in the header file and initialize it in the implementation file:

// .h
extern int foo;

// .cpp
int foo = 0

A more C++ way to do that can be something like this:

#ifndef GLOBAL_H
#define GLOBAL_H

struct Global {
static int foo;
};
#endif

And in your cpp file:

#include "variables.h"

int Global::foo = 0;

C++17 fixes this problem with inline variables, so you can do:

#ifndef GLOBAL_H
#define GLOBAL_H

inline int foo = 0;

#endif

See How do inline variables work? for more information.

Variable declaration in a header file

You should declare the variable in a header file:

extern int x;

and then define it in one C file:

int x;

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).

What is the most elegant way to work with global variables?

I am not sure that global variables are bad in all cases, but you really need to work hard to have very few of them (otherwise, your code in unreadable). For example <stdio.h> has stdout, and it won't be better if it was replaced by some FILE*get_standard_output(void); getter function.

As a rule of thumb, avoid having more than 4 or 5 global variables in your entire program (recall the magical number seven as a hint on our cognitive limitations).

However, you could pack (cleverly and with good taste, to keep your code readable) several related global variables into a single one of struct type. With your example, that could mean in your globals.h:

struct globalstate_st { int16_t v1, v2; };

then

extern struct globalstate_st gs;

and you would use gs.v1 instead of gVariable1; if you compile with optimizations, the performance of using gs.v1 is equivalent to using gVariable1.

BTW, if you have a multi-threaded program, you generally should protect global data with some mutex (or some other kind of synchronization or atomicity). Consider reading this pthread tutorial.



Related Topics



Leave a reply



Submit