C++变量由2个文件共享

noi*_*cat 2 c++ variables share pointers class

我有4个文件:

  • shared.h
  • main.cpp中
  • something.h
  • something.cpp

shared.h:

#ifndef SHARED_H
#define SHARED_H

int* sth;

#endif
Run Code Online (Sandbox Code Playgroud)

something.h:

#ifndef SOMETHING_H
#define SOMETHING_H

class foo
{
   public:
      void printVar();
};

#endif
Run Code Online (Sandbox Code Playgroud)

something.cpp:

#include <iostream>
#include "something.h"
#include "shared.h"

using namespace std;

void foo::printVar()
{
    cout<<"Foo: "<<*sth<<endl;
};
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

#include <cstdlib>
#include <iostream>
#include "shared.h"
#include "something.h"

using namespace std;

int main(int argc, char *argv[])
{
    sth=new int(32);

    foo x;
    cout<<"Main: "<<*sth<<endl;
    x.printVar();

    system("PAUSE");
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

编译器返回*sth的multipe定义;

我在*sth中添加了静态修饰符并编译,但崩溃了.我更改了打印以打印指针的地址,我返回了程序:

Main: 0x3e0f20
Foo: 0
Run Code Online (Sandbox Code Playgroud)

为什么没有分配foo的指针?我想在main中只分配一次,然后在其他文件中共享...我该怎么做?它是extern修饰符的东西吗?

Thanx任何回复.

Fle*_*exo 5

在shared.h中你想说:

extern int* sth;
Run Code Online (Sandbox Code Playgroud)

承诺某个地方存在的编译器.

然后在一个(也是唯一一个).cpp文件中你需要写:

int* sth;
Run Code Online (Sandbox Code Playgroud)

使其真正存在.通常,您可能希望了解声明和定义之间的区别.根据经验,您只想在头文件中声明事物,而不是定义它们.

当您static之前写过时,您说每个文件中都存在一个具有相同名称的变量,但每个文件都是"本地"变量,即sthmain.cpp 中的变量与sthsomething.cpp 中的变量不同.