公共头文件中的外部类以及类的头文件中的外部类

时间:2012-08-10 16:59:39

标签: c++

嗨,我不知道如何问这个问题我做了很多看,然后空了;所以如果已经过去,我必须道歉。我正在开发我的第一个c ++项目,它非常有趣。编译代码时出现重新定义错误。该项目由3个主文件组成,每个文件都有自己的头文件和一个共同的头文件。我希望我的其他文件可以访问这个类,所以我在公共头中声明了它。我写了警卫,所以我认为这样可以避免这个错误,但事实并非如此,我不明白为什么。

以下是相关的两个头文件。

menu.h


#ifndef MENU_H
#define MENU_H
#include "common.h"
class menu
{
   int x, y, iterations, time;
   void title(int maxX, int maxY);
   void titleSplash();
   void fall(bool, int&, int, int);

public:
menu();
void init();
int score;
void gameOver(int how);
void mainMenu();



};



#endif

common.h


#ifndef COMMON_H
#define COMMON_H
   //things that all files need
        #include <curses.h>
        #include <string.h>
        #include <cstring>
        #include <cstdlib> //for debugging
        #include <unistd.h>
        #include <iostream>


        //using namespace std;

        #ifdef _WIN32//are we running windows?

        #define _WIN32_WINNT 0x0600
        #define CLOCK 2//only used for the opening animaitons repalaces clock
        #define SLEEP(a) sleep(a);//in 1000s of a second
        #include "WIN32.h"
        #endif

        #ifndef _WIN32

        #define CLOCK 8
        #define SLEEP(a) usleep( a * 1000);//in 1 000 000s of a second// replaces CLOCK

        #endif

        #define TIMER 17 //for about 60 times a second rounding up form 16.666666

     #ifndef MAIN_H
        #ifndef NON_MAIN_COMMON
        #define NON_MAIN_COMMON

        //common things that i dont want to put in each header file




    #endif

#endif
//everything else if after here including everything common.cpp
//------------------------------------------------------------------------------------------

//anything in myLib MUST be externed to avoid multiple definitions error
#ifndef MYLIB_H
extern void getStdScr();
extern int stdx, stdy, score;
extern WINDOW * win;
extern void ncursesInit();
extern void wrapper();
extern void newGame();
extern std::string keyPress();
extern void bclear(WINDOW * window);
#endif

#ifndef MENU_H
class menu
{
public:
menu();
void init();
int score;
void gameOver(int how);
void mainMenu();
};
#endif

//end of myLib


#endif
//EOCOMMON

我认为menu.h和common.h中的警卫都会阻止重新定义我的菜单类。

2 个答案:

答案 0 :(得分:1)

为什么从您发布的代码中获得多个定义错误并不明显。但答案很简单。不要两次定义类菜单。我不明白你为什么这样做。你认为它有什么好处?只需将它放在common.h或menu.h中即可,你应该没问题。

当您说'项目包含3个主文件,每个文件都有自己的头文件和一个共同使用的标题'时,您似乎对头文件的作用有误解。但是头文件中的所有内容都是通用代码。这就是头文件的用途。因此,我的选择是将类菜单放在menu.h中,然后在任何需要的地方包含menu.h。

答案 1 :(得分:0)

如果您多次定义一个班级,那么您在common.h中错过了#define MENU_H(以及#define MYLIB_H),每次都需要整个警卫,而不仅仅是{{1}部分。

此外,您应该使用#ifndef MENU_H#include "menu.h",而不是再次定义菜单类。如果2个标题都包含另一个标题,那么这不是一个错误,只有当两者都需要先定义另一个标题时才会出现这种情况,但情况显然并非如此。

PS:有一个#include "mylib.h",所以不是

#else

你可以写:

#ifdef _WIN32
  // for windows
#endif
#ifndef _WIN32
  // for anything else
#endif