3

I know that global variables in C sometimes have the extern keyword. What is an extern variable? What is the declaration like? What is its scope?

This is related to sharing variables across source files, but how does that work precisely? Where do I use extern?

I want to know this so when the time arrives for my final project, I know how to do it.

7

From this really long answer:

Using extern is only of relevance when the program you're building consists of multiple source files linked together, where some of the variables defined, for example, in source file file1.c need to be referenced in other source files, such as file2.c.

Best way to declare and define global variables

Although there are other ways of doing it, the clean, reliable way to declare and define global variables is to use a header file file3.h 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. For each program, one source file (and only one source file) defines the variable. Similarly, one header file (and only one header file) should declare the variable.

file3.h

extern int global_variable;  /* Declaration of the variable */

file1.c

#include "file3.h"  /* Declaration made available here */

/* Variable defined here */

int increment(void) 
{
    return global_variable++;
}

file2.c

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

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

The next two files complete the source for prog1:

prog1.h

extern void use_it(void);
extern int increment(void);

prog1.c

#include "file3.h"
#include "prog1.h"
#include <stdio.h>

int main(void)
{
    use_it();
    global_variable += 19;
    use_it();
    printf("Increment: %d\n", increment());
    return 0;
}

prog1 uses prog1.c, file1.c, file2.c, file3.h and prog1.h.

1

the answer is wrong, please change it. see below for the correct file1.c from the really long answer:

#include "file3.h"  /* Declaration made available here */
#include "prog1.h"  /* Function declarations */

/* Variable defined here */
int global_variable = 37;    /* Definition checked against declaration */

int increment(void) { return global_variable++; }
2
  • can I do the opposite?like define a variable globally in .cc file and then use it in header file?
    – Nidhi Jha
    Mar 20 '20 at 1:37
  • why would you want to do that? there's almost definitely a better way to do whatever it is that you want to.
    – mahesh
    Mar 21 '20 at 5:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .