【发布时间】:2018-05-09 10:44:08
【问题描述】:
我正在尝试使用外部变量来获取我的一个头文件和我的主 .cpp 文件之间的数据。我为外部变量设置了一个 .h 文件。该文件名为 externTwo.h:
#include <string>
#include <vector>
#include "symbolTable.h"
#include <stack>
using std::stack;
extern stack<symbolTable*> parentalStack;
#endif
然后它应该在我的 .cpp 中使用:
#include "symbolTable.h"
//#include "node.h"
#include <FlexLexer.h>
#include<iostream>
#include<vector>
#include "externals.h"
#include "externTwo.h"
using std::vector;
using namespace std;
int yyparse();
yyFlexLexer scanner;
Node *tree;
extern std::vector<Node*> plantation;
extern std::stack<symbolTable*> parentalStack;
int main ()
{
symbolTable* base = new symbolTable();
std::vector<symbolTable*> theTable;
parentalStack.push(base); //put the top scope in
theTable.push_back(parentalStack.top());
}
最后在我的附加 .h 文件 (node.h) 中:
#ifndef NODE_H
#define NODE_H
#include<iostream>
#include<string>
#include <vector>
#include <stack>
#include "symbolTable.h"
#include "externTwo.h"
using std::string;
using std::endl;
using std::ostream;
using std::vector;
using std::stack;
extern stack<symbolTable*> parentalStack;
class Node
{ };
#endif
每当我尝试访问 main 中的 parentalStack 时,我都会收到“未定义对 `parentalStack' 的引用”错误。我很困惑为什么我在一个单独的外部文件中以相同的方式声明了外部种植园,并且能够从 main.xml 文件中很好地访问它。如果我尝试使用 parentalStack,我也会从 node.h 中得到同样的错误。
非常感谢!
【问题讨论】:
-
您可以将
extern视为大致意思是“此符号将在其他地方定义”。因此,您实际上需要在其中一个 cpp 文件中将其定义为非extern。 -
虽然如果你只有一个cpp文件,那么绝对没有理由在头文件中声明这个变量。
标签: c++ class pointers stack extern