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.

11 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

    http://farm4.static.flickr.com/3227/2821772213_2b6f515415_o.jpg

    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 :P

    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. :(

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>