2017-11-25 15 views
-1

extern 변수를 사용하여 헤더 파일과 주 .cpp 파일간에 데이터를 가져 오려고합니다. 외부 변수에 대해서만 .h 파일을 설정했습니다. 이 파일은 externTwo.h라는 제목 :C++의 Extern 변수

#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 

메인에서 parentalStack에 액세스하려고 할 때마다 "parentalStack '에 대한 정의되지 않은 참조가 수신됩니다. 나는 extern plantation을 별도의 extern 파일에서 같은 방식으로 선언하고 메인 내에서 잘 액세스 할 수있는 이유는 혼란 스럽습니다. parentalStack을 사용하려고하면 node.h에서도 동일한 오류가 발생합니다.

미리 감사드립니다.

+1

'extern'은 대략 "이 기호는 다른 곳에 정의됩니다"라는 의미로 생각할 수 있습니다. 그래서 당신은 실제로 그것을 당신의 cpp 파일 중 하나에서 'extern '이 아닌 것으로 정의 할 필요가있다. –

+2

하나의 cpp 파일 만있는 경우에도 헤더 파일에이 변수를 선언 할 이유가 없습니다. –

답변

1

extern을 cpp 파일에서 제거하십시오. 그것은 그것을 정의 할 것입니다. extern은이를 선언합니다. 정의하는 .cpp 파일이 하나만 있는지 확인하십시오.