Qt使用extern变量编译问题

问题描述

| 我有一个漫长的过程,它会产生大约700 Mb的txt日志输出文件。这很难管理。因此,我想将输出分成多个较小的日志文件。这就是我的main.cpp的样子
#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:在功能“2ѭERRORLOGGER\”中 /home/aarelovich/DropBox/mineSim/main.cpp:9:对“3ѭERRORLOGGER\”的未定义引用 /home/aarelovich/DropBox/mineSim/main.cpp:15:未定义对“4ѭmain\”的引用: /home/aarelovich/DropBox/mineSim/main.cpp:40:未定义对“5ѭERRORLOGGER\”的引用 collect2:ld返回1退出状态 谁能告诉我我在做什么错?或者如何动态更改在其中创建应用程序日志的输出文件? 谢谢你的帮助     

解决方法

        您的问题可能与extern变量有关。 这是如何在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;
    }
在您的示例中,如果您在logoutput.h中使用“ 8”, 就像在链接中说明的那样,需要在另一个cpp中声明此变量。 我希望这有帮助