Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use of global variables between two files in C

I need to use a global variable first declared in a .c file, and use later on two different .c files. Problem, I got an error message when I compile.

Here’s the declaration, there :

bool UP = false;

And here’s how I use it :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

extern bool UP;

And I got this error message. If I put these variables inside the second file, it compile perfectly,but due to the fact I need these variables in another file, I need to share it.

gcc -c game.c -lGL -lGLU -lglut
gcc -o program main.o loadMap.o draw.o game.o object.o menu.o -lGL -lGLU -lglut
/usr/bin/ld: game.o: in function `game':
game.c:(.text+0x34): undefined reference to `Keyboard'
/usr/bin/ld: game.c:(.text+0x95): undefined reference to `UP'
collect2: error: ld returned 1 exit status
make: *** [makefile:10: program] Error 1

EDIT : Here’s more source code.
This is .h file where I declare my variables

#ifndef KEYBOARD_H_
#define KEYBOARD_H_

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>


bool UP = false;
bool LEFT = false;
bool RIGHT = false;
bool DOWN = false;
bool UP_MENU = false;
bool DOWN_MENU = false;

void Keyboard(unsigned char key, int x, int y);

#endif

And I want to use it here :

void game(int mX, int mY, Player p)
{
    drawMap(mX, mY);            //afficher la carte
    drawPlay(p); //Affiche le player
    
    
    glutKeyboardFunc(Keyboard);     //fonction de glut gérant le clavier
    
    if (LEFT == true)
    {
        
        moveLeft(p);        //va se déplacer vers la gauche si on appuie sur q
        LEFT = false;
        
    }
    if (RIGHT == true)
    {
        
        moveRight(p);       //va se déplacer vers la droite si on apppuie sur d
        RIGHT = false;
    }
    if (UP == true)
    {
        moveUp(p);
        UP = false;
    }
    
    if (DOWN == true)
    {
        
        moveDown(p);
        DOWN = false;
    }


    glutPostRedisplay();//upload la position du joueur
}

>Solution :

You need to put variables’ definition to .c file.

In keyboard.h:

extern bool UP;

In keyboard.c:

bool UP = false;

Include keyboard.h in other c files to use UP.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading