C++ Global Variable Declaration

How to declare global variable in C?

/* a.h */
extern int globali; /* Declaration for compilation */
/* Visible here */

Later make sure you define in (exactly) one of the compilation units.

/* something.c */
int globali = 42; /* Definition for linking */

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

shared global variables in C

In the header file write it with extern.
And at the global scope of one of the c files declare it without extern.

Proper Global Variable definition/declaration

You want to initialize variables at the point they are declared whenever possible, regardless of their scope.

For global variables, if you don't initialize them when they are declared, you need to initialize them after your program starts running, which leaves open the possibility that the global will be used before this occurs. Classes, with constructors, will be default constructed, which can cause work to be done and thrown out when the variable is assigned its proper value.

Global variables have another problem: the order they are constructed/initialized is only partially defined by the language. If you have two global variables that are declared in different source modules, you do not know which one will be constructed first. This can lead to the static initialization order fiasco.

So you can run into problems if you initialize them, or different problems if you don't. This is one reason why global variables should be avoided.

What is the solution? You can wrap your global variables into an accessor function. This will ensure that the variable has been properly initialized. So rather than the plain declaration:

SomeType big = ReadBig();

you can place it into a function:

const SomeType &GetBig() {
static SomeType big = ReadBig();
return big;
}

This also has the advantage of having your global variable const, so that it cannot be changed if this is necessary.

How to access local and global variable with same name in C

You could cheat and create a pointer to the global i before declaring the local i:

void fun2( void )
{
int *ip = &i; // get address of global i
int i = 50; // local i ”shadows" global i

printf( "local i = %d, global i = %d\n", i, *ip );
}

EDIT

Seeing as this answer got accepted, I must emphasize that you should never write code like this. This is a band-aid around poor programming practice.

Avoid globals where possible, and where not possible use a naming convention that clearly marks them as global and is unlikely to be shadowed (such as prefixing with a g_ or something similar).

I can't tell you how many hours I've wasted chasing down issues that were due to a naming collision like this.

Global variables initialization in C header file

With the build tools and switches you are using, int my_var; acts mostly like a declaration that is not a definition. Multiple declarations of an object identifier are allowed.

int my_var = 0; is a definition. There should be only one definition.

Due to the history of C use and development, int my_var; is technically a tentative definition. If there is no regular definition of my_var in the translation unit (the source file being compiled, including all the files it includes), it acts as a regular definition.

However, then when you have this in a header file that is included in multiple source files, you have multiple definitions. When there are multiple definitions of the same object identifier with external linkage, the C standard does not define the behavior.

When there are multiple regular definitions, your build tools report an error. However, they treat definitions that came from tentative definitions differently: They allow them and coalesce them into a single definition. Again, this is due to the history of how C developed and was used. Also, this behavior changed in GCC recently. Prior to GCC version 10, tentative definitions were coalesced by default, as described above. With GCC 10 and later, tentative definitions are not coalesced, and multiple definitions will result in an error. The old behavior can be requested with the switch -fcommon.

To avoid tentative definitions, you should declare the identifier in the header as extern int my_var;, which is just a declaration and not a tentative definition, and you should have exactly one source file containing int my_var = 0;, which is a regular definition and not a tentative definition.

Additional information is here, here, and here.

In C++11, can you declare global variables and function prototypes on the same line?

The declaration says that function(x), a, b, and array[i] are all ints.

(This is the "old-school reading" of types - it always works in C, but C++ broke it; int *x can be read "*x is an int", but int &x can't be read "&x is an int".)

This has been fine since the early days of C (so, for half a century or so), and it's not limited to global declarations.

It's also very confusing, and you will not find many who think it's a good idea.

Most people have now given up on declaring more than one variable in a line.

It's less readable, easy to forget an initializer, and screens are capable of displaying many lines simultaneously these days.



Related Topics



Leave a reply



Submit