包括未声明的变量错误,循环引用C ++

时间:2016-06-26 09:55:31

标签: c++ include

有两个.hpp文件

fileSystemUser.hpp

#pragma once
#include "main.h"
#include "fileCommands.hpp"//!!!Problem
#include "fileObject.hpp"
class FileSystemUser {
    ...
    void start() {
        FileCommands fc;
        ...
    }
   ....
}

fileCommands.hpp

#pragma once
#include "main.h"
#include "stringService.hpp"
#include "fileSystemUser.hpp" //!!!Problem
#include "debug.hpp"
class FileCommands {
    int analyze(string command, FileSystemUser* fileSystem) {...}
}

我以这种方式建立:
•cmake -G“MinGW Makefiles”..
•make //我在mingw bin文件夹中复制并重命名了cmake-32.exe

打印后步骤构建的问题: 我有很多错误。所有这些都是关于未声明的FileSystemUser。我认为这个问题包括我在那些包括// !!!问题。

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这是一个典型的问题,名为"循环引用"。

在这种情况下,编译器首先尝试在FileSystemUser之前编译FileCommands,因此第二个是未声明的。

要解决这个问题,我已经完成了下一个问题: 将.hpp除以.h和.cpp并使用前向声明

//fileSystemUser.h
#pragma once
#include "main.h"
#include "fileObject.hpp"
class FileSystemUser {
    void start();
};

class FileCommands {
    int analyze(string command, FileSystemUser* fileSystem);
};

//fileSystemUser.cpp
#include "fileSystemUser.h"
void FileSystemUser::start() {
    //some code
}
//fileCommands.cpp
#include "fileSystemUser.h"
int fileCommands::analyze(string command, FileSystemUser* fileSystem) {
    //someCode
}

另一个变种.cpp和两个.h

//fileSystemUser.h
#pragma once
#include "main.h"
#include "fileObject.hpp"
class FileSystemUser {
    void start();
};
#include "fileCommands.h" //after we declare the FileSystemUser 

//fileCommands.h 
#pragma once
#include "main.h"
#include "fileObject.hpp"
class FileCommands {
    int analyze(string command, FileSystemUser* fileSystem);
};

所以要编译足够的decalration,这就是为什么它编译,在.cpp之后会编译成静态库和链接,所以当它链接all时声明并且没有问题。 https://habrahabr.ru/post/155467/有关于链接静态库的说明。