未定义对<namespace> :: <variable>的引用

Jam*_*mes 3 c++

我正在研究一些代码来标记何时对网站进行了更改.我在类中使用静态变量时遇到了问题,因此我想在命名空间中声明一个变量,并在进行更改时设置此== 1.

以下是我编写的一些简化代码来表示问题:

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
Run Code Online (Sandbox Code Playgroud)

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;
    }
    }
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

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
Run Code Online (Sandbox Code Playgroud)

任何有关这方面的帮助将不胜感激.我之前有多个声明错误,所以我介绍了#ifndef的东西,以及变量之前的extern.

Yak*_*ont 6

extern变量就像extern int changes_made;需要在某处创建存储一样.你所说的是"在链接阶段,你会发现有人会向你输出这个int类型名称的符号".

然后你没有遵守承诺,因为没有单位出口int testing::changes_made.

在一些.cpp文件中,您要链接上面的p.cpp和main.cpp(甚至可能是p.cpp),创建一个变量的实例,如下所示:

namespace testing {
  int changes_made = 0;
}
Run Code Online (Sandbox Code Playgroud)

并且您的链接器错误应该消失.