2012-05-25 88 views
2

我使用extern变量为我的应用程序类,所以我可以将类函数转发到glutDisplayFunction(funcPtr)。C++ extern变量不可见

main.cpp中:

#include "main.hpp" 

int main(int argc, char** argv) 
{ 
    gApp = new GameApp(); 
    return 0; 
} 

main.hpp:

#ifndef MAIN_HPP 
#define MAIN_HPP 
    #include "GameApp.hpp" 
#endif 

GameApp.hpp:

#include <GL/gl.h> 
#include <GL/freeglut.h> 

class GameApp 
{ 
    public: 
    int running; 

    GameApp(); 
    virtual ~GameApp(); 
    void resize(int width, int height); 
    void init(int argc, char** argv, int width, int height); 
    void draw(); 
    void update(); 
    void key_input(unsigned char key, int x, int y); 
}; 

extern GameApp *gApp; 

void display_clb() 
{ 
    if (!gApp) 
    { 
    return; 
    } 

    gApp->draw(); 
} 

这是输出:

g++  -o dist/Debug/GNU-Linux-x86/gravity build/Debug/GNU-Linux-x86/main.o build/Debug/GNU-Linux-x86/GBody.o build/Debug/GNU-Linux-x86/GameApp.o build/Debug/GNU-Linux-x86/GBodyList.o -lm -lGL -lglfw -lGLU -lglut 
build/Debug/GNU-Linux-x86/main.o: In function `main': 
/home/viktor/Documents/cpp/Gravity/main.cpp:6: undefined reference to `gApp' 
/home/viktor/Documents/cpp/Gravity/main.cpp:7: undefined reference to `gApp' 
/home/viktor/Documents/cpp/Gravity/GameApp.cpp:13: undefined reference to `gApp' 
/home/viktor/Documents/cpp/Gravity/GameApp.cpp:18: undefined reference to `gApp' 
build/Debug/GNU-Linux-x86/GameApp.o: In function `display_clb()': 
/home/viktor/Documents/cpp/Gravity/GameApp.cpp:23: undefined reference to `gApp' 
build/Debug/GNU-Linux-x86/GameApp.o:/home/viktor/Documents/cpp/Gravity/GameApp.cpp:28: more undefined references to `gApp' follow 
collect2: ld returned 1 exit status 
make[2]: *** [dist/Debug/GNU-Linux-x86/gravity] Error 1 
make[2]: Leaving directory `/home/viktor/Documents/cpp/Gravity' 
make[1]: *** [.build-conf] Error 2 
make[1]: Leaving directory `/home/viktor/Documents/cpp/Gravity' 
make: *** [.build-impl] Error 2 

我希望gApp在我的main.cpp和GameApp类中可见。

+0

'gApp'的定义在哪里? –

回答

8

这不是一个编译错误,它是一个链接错误。你变声明是可见的只是main.cpp很好,但你没有定义它的任何地方 - 即你不为变量分配空间的任何地方。

你需要一个(且只有一个),C++文件,用于定义变量。也许你main.cpp

GameApp *gApp; 

(你可以初始化太在那里,但是这是没有必要在这种情况下)。

+0

谢谢。正是我需要的。 –

4

这告诉编译器有一个名为gApp变量,但它被定义在别处:

extern GameApp *gApp; 

因为该定义不存在,链接器失败。

以下内容添加到另一个(也是唯一一个)源文件:

GameApp *gApp; 
+0

谢谢。我的错误是多么愚蠢。猜猜这发生在你编写代码并入睡时,然后继续第二天:) –

2

随着extern,你告诉了变量存在的编译器,但它位于其他地方。编译器认为你的变量存在,并

所有你需要做的就是在源的地方创建实际的变量。您可以通过简单地在某处添加诸如GameApp *gApp;之类的内容来完成此操作。例如在你的cpp文件中。

+0

添加另一个'extern'声明不会有帮助。 – Mat

+0

你完全正确,我在那里输入错误。 – user1003819

0

与从其他人以前的答案,你公布GAPP的存在,但你实际上并没有提供它。

再加一个单词:我建议你把gApp的定义放在一个“GameApp.cpp”文件(而不是GameApp.hpp)中,并将它的声明放在一个“GameApp.h”文件中。