错误:方法未在此范围内声明(但已包含)

Error: method was not declared in this scope (but it is included)

本文关键字:包含 声明 范围内 方法 错误      更新时间:2023-10-16

我有两个文件夹,f1和f2,它们在同一级别(有相同的文件夹为父)。在f1中,我有项目的源代码,在f2中,我有单元测试。

当我试图将项目中的文件包含到单元测试类中时,就会出现问题。我就得到这个:

natty:/tmp/test/f2$ qmake-qt4 .
natty:/tmp/test/f2$ make
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I/usr/include/qt4/QtTest -I../f1 -I. -o main.o main.cpp
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I/usr/include/qt4/QtTest -I../f1 -I. -o tcommon.o tcommon.cpp
tcommon.cpp: In member function ‘void tcommon::tCalculateMD5_str()’:
tcommon.cpp:21:50: error: ‘CalculateMD5’ was not declared in this scope
tcommon.cpp: In member function ‘void tcommon::tCalculateMD5_uint()’:
tcommon.cpp:43:50: error: ‘CalculateMD5’ was not declared in this scope
make: *** [tcommon.o] Error 1

怎么回事?相关文件中的代码为,test/f2/tcommon.cpp:

#include "tcommon.h"
#include <common.h>
// ...
void tcommon::tCalculateMD5_str()
{
    QFETCH(QString, string);
    QFETCH(QString, result);
    // THIS IS LINE 21 <-----------------------------------------------
    QCOMPARE(CalculateMD5(string), result);
}
// ...

这里是common.htest/f1/common.h(包括发现很好):

#ifndef COMMON_H
#define COMMON_H
#include <QtCore>
QString CalculateMD5(uint number);
QString CalculateMD5(QString str);
#endif // COMMON_H

这是一个无法编译的项目(3 kb):http://www.xx77abs.com/test2.rar

您的问题是您在f2/tcommon.h中复制了f1/common.h的标题保护。

修改为(in tcommon.h):

#ifndef TCOMMON_H
#define TCOMMON_H
//...
#endif // TCOMMON_H

,问题被修复,程序构建,你可以运行它。作为回应:fixed.zip(参见此回答的来源)