2012-12-17 2 views
3

웹 사이트를 변경하면 일부 코드가 작성됩니다. 클래스에서 정적 변수를 사용하여 문제가 발생했습니다. 그래서 네임 스페이스에 변수를 선언하고 변경이 이루어지면 this == 1로 설정하려고합니다.정의되지 않음 참조 <namespace> :: <variable>

수소 이온 지수 (pH) : :

#include<iostream> 
using namespace std; 

#ifndef p_H 
#define p_H 
namespace testing{ 

extern int changes_made; 

class p 
{ 
    public: 
    void changed(); 
    void print_change(); 
    void print_change_ns(); 
    private: 
    static int changes; 
    int info; 
}; 

} 
#endif 

p.cpp :

#include "p.h" 
#include<iostream> 

using namespace testing; 

int p::changes=0; 

void p::changed(){ 
    p::changes=1; 
    } 

void p::print_change(){ 
    cout << p::changes << endl; 
    } 

void p::print_change_ns(){ 
    if (testing::changes_made == 1){ 
    cout << 1 << endl; 
    } 
    else{ 
    cout << 0 << endl; 
    } 
    } 

MAIN.CPP :

다음

내가 문제를 표현하기 위해 작성한 몇 가지 간단한 코드입니다
#include<iostream> 
#include"p.h" 

using namespace std; 
using namespace testing; 


int main(){ 

p test1, test2, test3; 
test3.changed(); 
changes_made=1; 

cout << "test1 "; 
test1.print_change(); 
test1.print_change_ns(); 

cout << "test2 "; 
test2.print_change(); 
test2.print_change_ns(); 

cout << "test3 "; 
test3.print_change(); 
test3.print_change_ns(); 

p test4; 
cout << "test4 "; 
test4.print_change(); 
test4.print_change_ns(); 
return 0; 
} 

나는 오류 메시지가 표시됩니다.

p.o: In function `testing::p::print_change_ns()': 
p.cpp:(.text+0x45): undefined reference to `testing::changes_made' 
main.o: In function `main': 
main.cpp:(.text+0x9b): undefined reference to `testing::changes_made' 
collect2: ld returned 1 exit status 

이 문제에 대한 도움을 주시면 감사하겠습니다. 이전에 여러 선언 오류가있어서 #ifndef 항목과 변수 앞에 extern을 도입했습니다.

+8

난 당신이 어디'changes_made' 정의를 참조하지 않습니다 당신은 또한 정확히 하나의 소스 파일 (아마 p.cpp)에 대한 정의가 필요합니다. – chris

답변

5

externextern int changes_made;과 같은 변수는 어딘가에서 저장소를 만들어야합니다. 당신이 말한 것은 "연결 단계에서 누군가가 당신에게 int 형의이 이름의 상징을 내보낼 것입니다."라는 것입니다.

그러면 단위가 int testing::changes_made이 아니기 때문에 약속을 지키지 못했습니다. 위의 p.cpp 및 MAIN.CPP (어쩌면 p.cpp)로 연결하는 몇 가지 .cpp 파일에서

,이 같은 변수의 인스턴스를 생성 :

namespace testing { 
    int changes_made = 0; 
} 

하고 링커 오류가 사라져야합니다.

1

이 (가)testing::changes_made으로 헤더 파일에 선언되어 있습니다. 하지만 으로 정의되어 있지 않습니다.

int testing::changes_made; // no "extern"