我需要使用首先在 .c 檔案中宣告的全域變數,然后在兩個不同的 .c 檔案中使用。問題,我在編譯時收到一條錯誤訊息。
這是宣告,那里:
bool UP = false;
這是我使用它的方式:
extern bool UP;
我收到了這個錯誤資訊。如果我將這些變數放在第二個檔案中,它可以完美編譯,但由于我需要將這些變數放在另一個檔案中,我需要共享它。
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
編輯:這里有更多源代碼。這是我宣告變數的 .h 檔案
#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
我想在這里使用它:
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
}
uj5u.com熱心網友回復:
您需要將變數的定義放到 .c 檔案中。
在keyboard.h中:
extern bool UP;
在keyboard.c中:
bool UP = false;
將keyboard.h 包含在其他c 檔案中以使用UP。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/449998.html
下一篇:無法將printf重定向到管道
