2011-06-23 55 views
0

我有一個可以生成大約700Mb的txt日誌輸出文件的可靠過程。這很難管理。所以我想將輸出分成多個較小的日誌文件。這是我的main.cpp看起來像Qt編譯使用extern變量編譯的問題

#include <QtGui/QApplication> 
#include "mineedit.h" 
#include "logoutput.h" 
#include <iostream> 

void messageHandling(QtMsgType type, const char *msg){ 

if (ERRORLOGGER.isEmpty()){ 
    ERRORLOGGER = DEFERRORLOGGER; 
} 

std::cout << "In Message Handling" << std::endl; 
std::cout << "Writing to file" << ERRORLOGGER.toStdString() << std::endl; 

QFile file(ERRORLOGGER); 
file.open(QFile::Append); 
QTextStream stream(&file); 
switch (type) { 
case QtDebugMsg: 
    stream << msg << "\n"; 
    file.close(); 
    break; 
case QtWarningMsg: 
    stream << "WARNING: " << msg << "\n"; 
    file.close(); 
    break; 
case QtCriticalMsg: 
    stream << "CRITICAL: " << msg << "\n"; 
    file.close(); 
    break; 
case QtFatalMsg: 
    stream << "FATAL: " << msg << "\n"; 
    file.close(); 
    abort(); 
}  
} 

int main(int argc, char *argv[]) 
{ 
ERRORLOGGER = DEFERRORLOGGER; 
qInstallMsgHandler(messageHandling); 
QApplication a(argc, argv); 
MineEdit w; 
w.show(); 
return a.exec(); 
} 
[/CODE] 

而且我logoutput.h就像

#ifndef LOGOUTPUT_H 
#define LOGOUTPUT_H 

#include <QString> 

//----------------------------For outputting an error file------------------------------ 
#define   DEFERRORLOGGER    "/home/aarelovich/Documents/log.err" 
#define   FOLDER_OUTPUT_LOG   "./home/aarelovich/Documents" 
extern QString ERRORLOGGER; 

#endif // LOGOUTPUT_H 

現在,在我的代碼是我爲之: ERRORLOGGER = name_of_current_log_file。

但是我得到以下編譯錯誤: OBJ/main.o:在功能messageHandling(QtMsgType, char const*)': /home/aarelovich/Dropbox/MineSim/main.cpp:8: undefined reference to ERRORLOGGER ' /home/aarelovich/Dropbox/MineSim/main.cpp:9:未定義的引用ERRORLOGGER' /home/aarelovich/Dropbox/MineSim/main.cpp:13: undefined reference to ERRORLOGGER' /家/ aarelovich/Dropbox/MineSim/main.cpp:15:未定義參考ERRORLOGGER' obj/main.o: In function main': /home/aarelovich/Dropbox/MineSim/main.cpp:40:undefined參考ERRORLOGGER' obj/mineedit.o:/home/aarelovich/Dropbox/MineSim/mineedit.cpp:101: more undefined references to ERRORLOGGER'關注 collect2:ld返回1退出狀態

任何人都可以告訴我我做錯了什麼?或者我可以如何動態更改創建應用程序日誌的輸出文件?

感謝您的任何幫助

回答

3

您的問題可能與extern變量有關。

Here是如何在C++中使用extern關鍵字的示例。

請注意,C++和C在鏈接時與extern關鍵字有差異。

Basicall你需要做的是

global.cpp:

// declaration of g_nValue 
int g_nValue = 5; 

main.cpp中:

// extern tells the compiler this variable is declared elsewhere 
    extern int g_nValue; 

    int main() 
    { 
     g_nValue = 7; 
     return 0; 
    } 

如果您使用extern QString ERRORLOGGER;你的榜樣logoutput.h, 正如鏈接中所述,需要在另一個cpp中聲明此變量。

我希望這可以幫助

+0

非常感謝!那工作。這是我做的。我接受了變量ERRORLOGGER,並在main.cpp,Ala global.cpp示例中聲明瞭它的錯誤消息函數。然後我所做的就是當我想要使用的時候,我使用extern重新聲明它,就是這樣。 – aarelovich