Circuit Negma

C++, C, VB.NET, PCB, Electronics, Circuit Design

C Programming :: How to use a variable in multiple/different source files?

Posted by Circuit Negma on July 16, 2008


Created By: Hussein Nosair

What is the best way to declare and define global variables and functions?

Declaration vs. Definition:

1. Declaration is a statement of a programmatic entity (ex. variable, function, union, structure) to be referenced in other parts of a program/code, which has its definition somewhere else.

2. Definition is the actually description, allocated space and initialization of a declared programmatic entity (ex. variable, function, union, structure).

Purpose:

a global variable or function is a variable or function that need to be shared or accessed across several source files, keeping in mind that the definition and declaration is consistent with each other.

Right                                                             Wrong

Definition:

int a;                                                             int a;

Declaration:

int a = 0;                                                       char a = 0;

OR

a global variable or function is a variable or function that need to be shared or accessed within a single source file, keeping in mind that the definition and declaration is consistent with each other.

*** The best way to declare and define a global variable is to place the declaration in a header file (.h) and the definition is a source file (.c).

How-to:

To define a global variable or function; you need to do the following:

1. create a header file with the declaration of variable or function.

Ex:

Common.h

#ifndef _COMMON_H_
#define _COMMON_H_

extern int i;
extern int n;
extern unsigned char Array[];

extern void func1();
extern int func2();

#endif

*** Note: The keyword extern is optional in function declarations

2. create a source file with the definition of variable or function.

Common.c

#include "common.h"

int i;      // Define i and initialize
int n;      // Define n and initialize

unsigned char Array[6] = {1,2,3,4,5,6};   // Define Array and initialize

// Define func1 and initialize
void func1(void)
{
    printf("This is ... function 1 \n");

}

// Define func2 and initialize
int func2(void)
{
    printf("This is ... function 2 \n");

    return 0;
}

*** Note: The declaration source file should include (#include) the definition header file.

3. Main program

#include <stdio.h>              // Include general I/O library
#include "common.h"             // Include defined variables and functions


void func3(void);               // Define Local function
void func4(void);               // Define Local function

int main(void)                  // Main Program
{
    printf("i = %d \n", i);     // Print out initial value of i
    printf("n = %d \n", n);     // Print out initial value of n

    i = 8;                      // Set a new value for i
    printf("i = %d \n", i);     // Print out the new value of i

    n = 4;                      // Set a new value for n
    printf("n = %d \n", n);     // Print out the new value of n

    func1();                    // Call global function = function 1 
    func2();                    // Call global function = function 2

    for(i=0; i<6; i++)          // Print out global Array
        printf("%d", Array[i]);

    // Print out blank lines
    printf("\n");
    printf("\n");

    func3();                   // Call local function = function 3

    // Print out blank lines
    printf("\n");
    printf("\n");

    func4();                   // Call local function = function 4

    return 0;                  // End main program

 }


// Definition of local function 3
void func3(void)
{
     printf("This is ... Function 3 \n");
     printf("Please, Enter a new value for variable i = ");
     scanf("%d", &i);
     printf("The new value for variable i = %d \n", i);

}

// Definition of local function 4
void func4(void)
{
     printf("This is ... Function 4 \n");
     for(i=0; i<6; i++)
     {
          printf("Please, Enter a new value for variable Array[%d] = ", i);
          scanf("%d", &Array[i]);
     }

     for(i=0; i<6; i++)
        printf("a new value for variable Array[%d] = %d \n", i, Array[i]);

}

*** Note: Need to include (#include) the definition header file wherever the global variables and functions  are needed in the program code.

16 Responses to “C Programming :: How to use a variable in multiple/different source files?”

  1. Kevin Li said

    Hi,

    Thanks for the information. I have a question:

    why defining i & j in ‘common.h’, the key word
    ‘static’ is not used?

    Thanks,

    Kevin

  2. Kevin Li said

    Sorry, it should be in ‘common.c’.

  3. defining i & n in ‘common.h’ will allow me to share those to variables across the entire project in case I need to access i & n in another source file.

    for example, I might have a lcd.c source file. for me to access and share i & n back and forth; I need only to include common.h in lcd.c source file.

    ex:
    #include “common.h”

    now lcd.c can read and write to i & n variables.

  4. variables that are declared globally, are by default set to static variables by the compiler.

    since we have used the word ‘extern’ in the declaration statement of i & n, we do not need to include the word static, because ‘extern’ will take care of setting up those variables as static variables.

    the word ‘extern’ will set a variable as a static variable and visible to all source files in the project.

    the word ‘static’ is much used when you need to define global variables within a single source file and not to be shared with other source files in the project. thus, the scope of those global variables are only known to the source file that are being defined in it.

    you could copy and paste the above codes into a new project then add the world ‘static’ in header file only and try to compile the project. then remove ‘static’ from header file and include them in the ‘common.c’ source file and compile the project. then see for your self that the compiler will complain about using the word ‘static’.

    I hope this would clear every thing for you.

  5. Mohit said

    I am getting error while running main program .It says undefined reference to variable…

    Please clarify.

  6. To Mohit,

    sorry for not responding as soon as possible.

    I am not sure to why you are getting error, so I have included the following zipped project file for Dev-C++ v4.9.9.2

    Right click on the above link and save it to you harddisk, then open this picture using WINRAR or WINZIP to extract the project’s files

  7. Dennis said

    Hey THX A WHOOOOOOLE LOT!!!!

    been pondering about this question for the whole day now and been searching and searching and didnt get ath (more like i don’t know exactly what keyword to use for the search….tried “using variables in different C files” or sth liddat 😛

    anyway stumbled into this page and WALA eth solved!!! Very much appreciated!!!

    btw am doing some PIC programming with many .c files for different parts of the program, built seperately. And now when i try combining those parts into one only then i realised this GLOBAL VARIABLE problem thingy…..and now its solved! …oh yea~

  8. debayan said

    what is the need for common.c file? is it not possible to initialize the variables/functions in the main program after including common.h header?

  9. To Debayan,

    It is possible to initialize the variables/functions in the main program after including common.h header in the main program, but doing so, on a large scale software will cause you problems of keeping track of all of the variables and functions.

    by defining the common.c file, you will be more organized and be able to change/modify variables and functions easily for large programs.

    it also always you to reuse common.c and common.h files in other projects. where as if you define and initialize your variables and functions in the main program, you will not be able to use these variables and functions in other future projects.

    think of common.h and common.c as a one packaged library, that can be used and reused over and over again across multiple projects.

    Also, by using such structure, you will be able to read and scroll through your main program and codes easily. Imaging you have a program that is 2000 lines long all jammed into one main file. if you are using one those basic IDEs, you will have problem reading, debugging and analyzing you code. where as if you break your code into headers and declaration files, your main code will shrink down to a couple of 100 lines that you will be able to read, manage, debug, and analyze easily.

  10. xCruiser said

    How do you open up that picture file? :-s Sorry but I don’t know how to extract it and I, too, am having problems with global variable and using it in different files. Please do help me. It’s giving me some linkage error. 😦

  11. Paul John S. Munion said

    Hello can you help me how to separate my stack program into multiple files including the global declaration in C? here is my program Plz Help thnaks. I dont know what to do ti fix this error…

    Global.h
    ************
    #include
    #include
    #include
    #define MAXSIZE 10

    struct st
    {
    int top;
    int stack[MAXSIZE];
    };
    struct st s;
    ***********************************************

    init.c
    *******
    #include “Global.h”
    struct in
    {
    char ans;
    int ch;
    };
    struct in initialize;
    ***********************************************

    main.c
    *********
    #include “Global.h”
    void main()
    {
    init();
    imple1();
    imple2();

    }
    *********************************************

    imple2.c
    ************
    #include “Global.h”
    int empty(void);
    int full(void);
    void push(void);
    void pop(void);
    void display(void);
    int full(void)
    {
    if (s.top == MAXSIZE)
    return(1);
    else
    return(0);
    }

    int empty(void)
    {
    if (s.top == 0)
    return(1);
    else
    return(0);
    }
    void push(void)
    {
    char ch;
    int x; //
    do
    {
    if(full() == 1)
    {
    printf(“\nStack Full\n”);
    break;
    }
    else
    {
    s.top = s.top + 1;
    printf(“\nEnter An Element To Be Pushed: “);
    scanf(“%d”,&x);
    s.stack[s.top] = x;
    }
    printf(“\nDo You Want To Push More Elements[y/n]”);
    flushall();
    ch = getch();
    }
    while(ch == ‘y’|| ch == ‘Y’);
    }

    void pop(void)
    {
    char ch;
    do
    {
    if(empty() == 1)
    {
    printf(“\nStack Empty\n”);
    break;
    }
    else
    {
    printf(“\n%d has been popped !”,s.stack[s.top]);
    s.top = s.top – 1;
    }
    printf(“\nDo you Want To Pop Out More?[y/n]”);
    flushall();
    ch = getch();
    }
    while(ch == ‘Y’|| ch == ‘y’);
    }

    void display(void)
    {
    int i;
    clrscr();
    if(empty() == 1)
    printf(“\nStack Empty!!!”);
    else
    {
    printf(” Displaying Stack…………\n”);
    for(i = s.top; i>0;i–)
    textcolor(GREEN);cprintf(” %d “,s.stack[i]);
    }
    }
    ************************************************************************

    imple2.c
    ***********
    #include “Global.h”
    do
    {
    clrscr();
    printf(“********Stack Program**********\n”);
    printf(“1.PUSH\n”);
    printf(“2.POP\n”);
    printf(“3.DISPLAY\n”);
    printf(“4.QUIT\n”);
    printf(“Enter Your Choice : “);
    scanf(“%d”,&initialize.ch);
    switch(initialize.ch)
    {
    case 1:
    push();
    break;
    case 2:
    pop();
    break;
    case 3:
    display();
    break;
    case 4:
    exit(1);
    break;

    default:
    printf(“INVALID CHOICE!!!!!!!!!!!!!!!!\n”);
    break;
    }
    printf(“Want To Go To The Main Menu[y/n]”);
    flushall();
    initialize.ans = getch();
    }
    while(initialize.ans == ‘y’ || initialize.ans == ‘Y’);
    printf(“\nPress Any Key To Exit”);
    getch();
    ***************************************************************
    I hope you could help me. thanks.. PJ

    • I am not sure if I understand your request, but I will try this and hopefully it is the answer you are looking for:

      1. Create a file called Global.h
      — Copy and paste the following into Global.h

      #ifndef __GLOBAL_H
      #define __GLOBAL_H

      #include “xxxxxx.h”
      #include “xxxxxx.h”
      #include “xxxxxx.h”
      #define MAXSIZE 10

      struct st
      {
      int top;
      int stack[MAXSIZE];
      };
      struct st s;
      ***********************************************

      2. Create a file called init.c
      — Copy and paste the following into initl.c

      #define __INIT_C // Optional
      #include “Global.h”
      struct in
      {
      char ans;
      int ch;
      };
      struct in initialize;
      ***********************************************

      3. Repeat the above steps for the other files.
      4. All created files must be in the same Project directory

  12. Get Design said

    Hi there, I read your blog on a regular basis. Your humoristic style is awesome,
    keep up the good work!

  13. c_coder said

    I have a question:
    Say, that we have a bigger project and many files include common.h (it is named common.h so this seems reasonable?). I’m not sure but isn’t it so that for each c-file that include common.h, there will be a new instance of Array in memory?

    (if that is the case maybe this would cause problems if Array would contain many elements and in systems that have small amount of memory?)

    • let’s say for example that we define an array in the common.h:
      int counter[6];

      the C compiler will recognize that array counter[6] is a global variable and not instance variable, thus the C compiler will create only one counter[6] to be shared by any c-file that call out for common.h file.

      Let’s say you have the following setup:
      File 1:
      common.h
      int counter[6];

      File 2:
      main.c
      #include “common.h”
      … <—- at this point the compiler will create a global variable called counter[6];

      int counter[6]; <—- compiler is going to create a local variable called counter[6]. This variable is shared among functions defined in the main.c file ONLY
      this variable has nothing to do with the one defined in the common.h file


      fun1(); <—- we call out func1
      fun2();

      void fun1(void)
      {
      int counter [6]; <—- at this point the compiler will create an instance/local variable called counter[6] this is only accessible to fun1
      …. an it is different from the global variable counter[6] defined in the common.h
      }
      <—– once we exit fun1, the compiler will destroy the instance/local variable created under fun1.

      As you can see the compiler will manage the location of all the variables you define wither they are global or local or instance such as the one in define in fun1().

      And one more thing, try the above example to make sure that your compiler support the reuse of variable's name. I did read somewhere that c compilers are different from one to another.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.