嗨,我不知道如何提出這個問題,我已經完成了相當多的工作,並且空着;所以我必須道歉,如果這已經過去了。我正在開發我的第一個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將防止重新定義我菜單類。
類不應該在COMMON.H。只在menu.h中。而externs只在mylib.h中。爲什麼他們是extern?那些不是全局變量 – Gir 2012-08-10 17:03:04
無法重現。發佈一個最小的完整示例,否則我們將沒有機會。 – Beta 2012-08-10 17:15:46
如果你在兩個不同的地方有相同的代碼,他們會*不同步。不要重複自己;這是編程最基本的規則之一。 – 2012-08-10 19:27:41